Professional Documents
Culture Documents
Pointers, Strings and Structures
Pointers, Strings and Structures
Cont’d…
Declaration of Pointers
If we declare a pointer variable and include and
initializer:
int *ip3 = &i;
we’re setting the initial value for ip3, which is where
ip3 will point. The initial value is a pointer.
The * in the above declaration is not the contents-
of-operator, but it is the indicator that ip3 is a
pointer.
Cont’d…
Declaration of Pointers
If you have a pointer declaration containing an
initialization, break it up to a simple declaration
and a conventional assignment, like this:
int *aptr, a;
aptr = &a;
Cont’d…
Declaration of Pointers
When a pointer is declared, it does not point anywhere. You
must set it to point somewhere before you use it. So,
int *ip;
*ip = 100; /* WRONG! */
Cont’d…
Consider the effect of the following code:
ip = &x;
y = *ip;
x = ip;
*ip = 3;
int x = 10, y = 5; x 10 y 5 ip
100 200
x 10 y 10 ip 100
y = *ip; 100 200 1000
*ip = 3; x 3 y 10 ip 100
100 200 1000
#include <iostream>
using namespace std;
int main()
{
int x, *xptr;
x=10;
xptr=&x;
cout<< "\nThe address of x is : "<<&x
<<"\nThe value of xptr is : "<<xptr;
cout<<"\n\nThe value of x is : "<<x
<<"\nThe value of *xptr is : "<<*xptr;
cout<<"\n\nShowing that * and & are inverses of each other :\n"
<<"&*xptr = "<<&*xptr<<"\n*&xptr = "<<*&xptr
<<endl;
return 0;
}
output
Calling functions by reference
In this chapter, we’ll look at the call-by-
reference with pointer arguments
Pointers can be used to modify one /more
variables in the caller or to pass pointer to
large data.
When calling a function with arguments that
should be modified, the address of the
arguments are passed, by using the operator
(&) to the name of the variable to pass.
#include <iostream>
using namespace std;
void cubebyValue(int x)
{ x*=x;
}
Passing pointer to a function
4 ways to do so :
i. a nonconstant pointer to nonconstant data
ii. a constant pointer to non constant data
iii. a nonconstant pointer to constant data
iv. a constant pointer to constant data
int main()
{
int x,y;
*ptr=10;
ptr=&y ; // ERROR!
return 0;
}
a constant pointer to a constant data
a pointer always point to the same memory location
and the data at that memory cannot be modified
using the pointer.
Pointer expression & pointer
arithmetic
A limited set of arithmetic expressions may be
performed o pointers
Pointer maybe incremented(++) or decremented(--)
Integer may be added (+=,+) to a pointer, subtract
from a pointer
Any arithmetic operations for pointers are based on
the size of the data type being used by the machine –
pointer arithmetic is machine dependent.
Pointers Arithmetic
Example:
int v[5];
int *vp;
vp = v; /* array name refer to 1st
element, v[0] */
location
3000 3004 3008 3012 3016
Cont’d…
vp
Pointers Arithmetic
If an integer is stored in 4-bytes of memory
vp += 2; (3000 + 2*4) = 3008
size of memory
location
3000 3004 3008 3012 3016
Output :
8
6
12
Relationship Between Pointers and Arrays
Arrays and pointers closely related
Array name like a constant pointer
Pointers can do array subscripting operations
Define an array b[ 5 ] and a pointer bPtr
To set them equal to one another use:
bPtr = b;
The array name (b) is actually the address of first
element of the array b[ 5 ]
bPtr = &b[ 0 ]
Explicitly assigns bPtr to address of first element of b
Relationship Between Pointers and Arrays
Element b[ 3 ]
Can be accessed by *( bPtr + 3 )
Where 3 is called the offset. Called pointer/offset
notation
Can be accessed by bptr[ 3 ]
Called pointer/subscript notation
bPtr[ 3 ] same as b[ 3 ]
Can be accessed by performing pointer arithmetic on
the array itself
*( b + 3 )
Pointer and Arrays
Cont’d…
const int size=3;
int main()
{
int s[size]={5,10,15};
int *sPtr,i;
sPtr=s;
for(i=0;i<size;i++)
{
cout<<"*s["<<i<<"] = "<<*(s+i)
<<"\t*sPtr["<<i<<"] = "<<*(sPtr+i)
<<endl;
}
cout<<endl;
return 0;
}
int main()
{
char string[10]="good luck";
char *str;
str=string;
for(;*str!='\0';str++)
{
cout<<*str;
}
cout<<endl;
return 0;
}
Array of Pointers
We can have arrays of pointers since pointers are
variables.
e.g:
char *text[3] = {“teh”, “susu”, gula”};
for(i=0;i<size;i++)
{
cout<<*(s+i);
}
Strings
A string is a series of characters treated as a single unit
(array of characters, ending with null (‘\0’))
A string may include letters, digits and symbols
String literals/ string constant are written in “ “, such as
“Abdullah Azzam,”, “99 21 Jump Street”, “AG100”
Example of declaration :
char state[] = “kelantan”; or char *statePtr=“Johor”;
char name1[30], name2[30];
cout<<“name1 : ”;
cin.getline(name1,30);
cout<<“name2 : ”
cin>>name2;
cout<<“/n”<<name1<<endl<<name2;
String manipulation: <cstring>
Function Description
strcpy(string1,string2) Copies string2 to string1.
int main()
{char s1[]={"kedah darul aman"};
char s2[17],s3[11] ,s4[20]="negeri ";
cout <<"The string in s1 is : "<<s1<<endl
<<"The string in s2 is : "<<strcpy(s2,s1)<<endl
<<"The string in s3 is : ";
strncpy(s3,s1,11);
s3[11]='\0';
cout<<s3;
cout<<endl;
cout<<"strcat(s4,s3) = "<<strcat(s4,s3);
return 0;
}
char *s1= "Selamat Menyambut Bulan Ramadhan" ;
char *s2="Selamat Menyambut Bulan Puasa";
cout<<"s1 = "<<s1<<endl
<<"s2 = "<<s2<<endl;
if (strcmp(s1,s2)==0)
cout<<"s1 and s2 have the same string";
else cout<<"s1 and s2 are different";
cout<<endl;
int main()
{char s1[]="Ahlan ya Ramadhan" ;
char *token;
cout<<"The length of \""<<s1<<"\" is : "<<strlen(s1)<<endl;
//cout<<"s1 = "<<s1<<endl;
cout<<"Setelah di token kan: "<<endl<<endl;
token=strtok(s1," ");
while(token!=NULL)
{
cout<<token<<endl;
token=strtok(NULL," ");
}
cout<<endl;
return 0;
}
Structures
Structures
Collections of related variables (aggregates) under
one name
- Can contain variables of different data types
- Commonly used to define records to be stored in files
For example, we might want to group three strings (name,
address, and phone number) into one structure
Sometimes we want to use the entire structure (i.e., for
moving to secondary storage)
Sometimes we want to use just a single member of the
structure
Structure Definitions
Structures are user defined data types
This means that we have to tell C++ the makeup of
our structure
We must provide a structure definition
Structure Definition Format
• The structure definition follows the format:
struct tag {member definitions};
– The tag is the name of our new data type
(equivalent to int or float)
– In member definitions we define each of the
individual variables that make up the structure
struct employeeRecord
{
char name[30];
int empNo;
float payRate;
};
Structure Declarations
The definition does not allocate any memory
Member definitions are not variable declarations, they
just tell C what the structure contains
We must declare a variable of our structure just like we
would an int or float
The keyword struct must be included whenever a structure
data type is referred to
struct employeeRecord
{
char name[30];
int empNo;
float payRate;
};
struct employeeRecord fullTime;
Definitions/Declaration
We can define and declare structures in the same
statement
struct tag
{member definitions}
variable names;
The names are the identifiers of the variables of the
data type named tag
The tag is optional in this case, but if we leave it off we
can not declare more variables of this type at a later
point
Definition/Declaration Examples
With the tag:
struct employeeRecord
{
char name[30];
int empNo;
float payRate;
} fullTime, partTime;
struct employeeRecord
{
char name[30];
int empNo;
float payRate;
}
struct employeeRecord fullTime={“Abdullah”, 444, 12.63};
fulltime.name =“Abadi”;
Fulltime.empNo= 101;
Accessing Structures
We usually want access to the individual members of the
structure
We use the variable name, member name, and member
operator to access these
The member name is the variable that is part of the structure
int main(void)
{
struct employeeRecord fullTime = {"Abdullah",001,150.00};
return 0;}
Passing and Returning Structures
struct
{ int idNum;
double payRate;
double hours;
} emp;
void main()
{
struct vegetable veg1, veg2;
struct vegetable addname();
void list_funct(vegetable);
veg1= addname();
veg2= addname();
cout<<“\n Vegetable for sale\n”;
list_funct(veg1);
list_funct(veg2);
}
continue
//this function returns a structure
struct vegetable addname( )
{struct vegetable vege;
cout<<“\n Vegetable name : ”;
cin>>vege.name;
cout<<“Price (per 100gm) : ”;
cin>>vege.price;
return(vege);
}
void list_funct (vegetable list)
{ cout<<“\n Vegetable name : ”<< list.name;
cout<<“\n Vegetable price : RM ”<< list.price;
}
Arrays of Structures
You can have arrays of structures, just like any other data type
struct tag variableName [numberOfElements] ;
• You can also initialize an array of structures
struct studentRecord
{ char name[25];
int m1; float x;
};
struct studentRecord students[4] = { {“Zaid Akhtar”, 5, 12.63},
{“C.K Tan”, 0, 9.50}, {“ G.Gobala”, 3, 10.83},
{“Cik Lela Manja”, 5, 15.25}};
Array of Structures Example
#define NUM_OF_EMPLOYEES 2
#define NAME_CHRS 30
void main(void)
{
struct employeeRecord
{ char name[NAME_CHRS];
int dependents;
float payRate;};
struct employeeRecord employees [NUM_OF_EMPLOYEES];