C pointer is a memory address. When you define a variable for example:
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
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:
Now if you want pointer px to points to memory address of variable x, you can use address-of operator (&) as follows:
After that you can change the content of variable x for example you can increase, decrease x value :
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:
Here is the output for code snippet
value of pc is 1310580
value of pc is 1310576
value of y is 10
0 comments:
Post a Comment