Pointer

Can any one explain what pointer do in the code

1
2
3
4
5
6
7
8
9
10
11
12
13
 #include<iostream>
using namespace std;

int main( )
{
int x[6]={2,3,4,5,6,7};
int *end=x+6;
for(int *p=x;p<end;p++)
cout<<*p;

return 0;
}


... and explain the difference between (*end=x+6;) and ( *end=l+6; )>>here i get error >>if i add int l in the up code .
Try to rewrite the loop using an index for the array and you will see the difference.
The program prints the numbers:
234567

Define Array:
[quote=http://www.cplusplus.com/doc/tutorial/arrays/]An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.[/quote]

int *end=x+6;
This says set the variable 'end' to point to the past-the-end element in the array

Define past-the-end element:
[quote=http://www.cplusplus.com/reference/vector/vector/end/]The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.[/quote]

int *p=x;
The variable x is always pointing to the first element in the array, so setting *p to x will also point p to the first element in the array.

p<end;
Loop while the distance from p to end is greater than 0

cout<<*p;
Print the value the pointer p is pointing to. If this had been changed to:

cout<<p;
This will print the memory address p is currently pointing at

p++ add an index to a unique identifier


Code can also be rewritten as:
1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
using namespace std;

int main( )
{
	int x[]={2,3,4,5,6,7};
	for(int p = 0; p < 6; p++)
		cout<<x[p];

	return 0;
}
Last edited on
Thanks all
Topic archived. No new replies allowed.