Monday, January 25, 2010

Pointer in C

We discussed pointer in C language in today's OOP344 class, and I understand some concepts which I get confused before.

Below is an example:
1 int a = 10;
2 int* p = &a;
3 printf("%u, %u, %d, %d\n", p, &a, *p, a);
4 p++;
5 printf("%u, %u, %d, %d\n", p, &a, *p, a);

The output of the second printf confuses me. I thought the last two number should be the same and unknown. In fact, that's not the case.
In line 4, only the value of p changed, the value of a remained the same. If I want the value of the last two number which are to be printed on line 5 to be the same, then I should code :
(*p)++; //++ has higher priority than *
Then both *p and a will be 11.

Another example
int a[5] = {1,2,3,4,5};
int* p = a;
The addresses of p and a are the same, rather than in different location but pointing to the same position.

In addtion, we can have a pointer pointer. It is like this:
int* p = &a;
int** q = &p;
In this way, we can manipulate the pointer pointing to other places inside a function.

No comments:

Post a Comment