Thursday, January 20, 2011

17.Pointers


C pointer is a memory address. When you define a variable for example:
1int x = 10;
You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of variable x, you use operator & before it. This code snippet print memory address of x
1printf("memory address of x is %d\n",&x);
and in my PC the output is
memory address of x is 1310588
Now you want to access memory address of variable x you have to use pointer. After that you can access and modify the content of memory address which pointer point to. In this case the memory address of x is 1310588 and its content is 10. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows:
1int *px;
Now if you want pointer px to points to memory address of variable x, you can use address-of operator (&) as follows:
1int *px = &x;
After that you can change the content of variable x for example you can increase, decrease x value :
1*px += 10;
2printf("value of x is %d\n",x);
3*px -= 5;
4printf("value of x is %d\n",x);
and the output indicates that x variable has been change via pointer px.
value of x is 20
value of x is 15
It is noted that the operator (*) is used to dereference and return content of memory address.
In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address. In this cases, you can use const keyword to define a pointer points to a constant integer or a constant pointer points to an integer as follows:
01int c = 10;
02int c2 = 20;
03
04/* define a pointer and points to an constant integer.
05pc can point to another integer but you cannot change the
06content of it */
07
08const int *pc = &c;
09
10/* pc++; */ /* cause error */
11
12printf("value of pc is %d\n",pc);
13
14pc = &c2;
15
16printf("value of pc is %d\n",pc);
17
18/* define a constant pointer and points to an integer.
19py only can point to y and its memory address cannot be changed
20you can change its content */
21
22int y = 10;
23int y2 = 20;
24
25int const *py = &y;
26
27*py++;/* it is ok */
28printf("value of y is %d\n",y);
29
30/* py = &y2; */ /* cause error */
Here is the output for code snippet
value of pc is 1310580
value of pc is 1310576
value of y is 10

Dont Miss Another Post Connect With Us !

Enter your email address:

0 comments: