


































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



































Wednesday, April 25, 2012
You cannot add two pointers
You can subtract two pointers (if they are of same base type). •
Other than addition or subtraction of a pointer and an integer, or the subtraction oftwo pointers, no other arithmetic operationscan be performed on pointers. •
You cannot add or subtract float or double values.
Pointer Arithmetic
In C++, there is a close relationshipbetween pointers and arrays.
Pointers and Arrays
Pointers and Arrays
Pointers and Arrays
int i1[4]={55,26,17,68};int i2[4]={11, 2, 53, 14};i2=i1; //NOT ALLOWEDchar str1[]=“i am a string”;char str2[]=“i am a string”;Pointers may be compared in C++ using relationaloperators like >, >=, <, <=, == etc, but they must havesome relationship to be meaningful
Pointers and Arrays
**int i1[4]={55,26,17,68};int i2[4]={11,2,53,14};int p1;p1 = i1;int p2;p2 = p1;
//this is ok
Pointers and Arrays
int *y_ptr, *another_ptr, y=45;y_ptr=&y;another_ptr=&y;
/*what is *another_ptrwhat is y_ptr/
cout << (another_ptr==y_ptr) << endl;
Pointers
*int b[] = {10, 20, 30, 40};int bPtr;bPtr = b;
// set bPtr to point to array b
cout << "Array b printed with:" << endl
<< "Array subscript notation" << endl; for (int i = 0; i < 4; i++)
cout <<b[i] << endl;
cout << "Pointer subscript notation" << endl;
for (i = 0; i < 4; i++)
cout << bPtr[i] << endl;
//Another way to do this?
Using subscripting and pointer notations with arrays
int offset;
cout << "Pointer/offset notation where" << endl
<< "the pointer is the array name" << endl;
for(offset = 0; offset < 4; offset++)
*cout << (b + offset) << endl;
cout <<"Pointer/offset notation" << endl; for(offset = 0; offset < 4; offset++)
*cout << (bPtr + offset) << endl;
Using subscripting and pointer notations with arrays
0x0012FEBC
0x0012FEBC
0x0012FEBC
0x0012FEBC
Using subscripting and pointer notations with arrays
int a[5]={12, 3, 45, 5, 8};int ptr;ptr=a;cout<<a[0]<<endl;cout<<ptr[0]<<endl;cout<<(a+0)<<endl;cout<<(ptr+0)<<endl;cout<<a[1]<<endl;cout<<ptr[1]<<endl;cout<<(a+1)<<endl;cout<<*(ptr+1)<<endl;
Using subscripting and pointer notations with arrays
int i1[4]={55, 26, 17, 68};What is wrong with the following statement?i1++;//The following is ok int
*i_ptr;
i_ptr
i1;
i_ptr++;cout<<i_ptr;* //The following is ok
*(i1+3) = 100;
// This is OK because i1 has not changed
Pointers and Arrays
int b[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};int *bPtr;bPtr= b;
// set bPtr to point to array b
/* set b2Ptr to point to sixth element of array b */ int *b2ptr; b2ptr = b+5; //Remember pointer arithmetic?
cout << "b[" << 5 << "] = " << b[5] << endl;cout << "*b2ptr= " << *b2ptr << endl;cout << "(b2ptr - bPtr) = " << (b2ptr - bPtr);
Pointers and Arrays