Trang chủ » C/C++ » C Pointer

C Pointer


C pointer is a memory address. When you define a variable for example :

int 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

printf("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:

 

int *px;

Now if you want pointer px to points to memory address of variable x, you can use address-of operator (&) as follows:

int *px = &x;

After that you can change the content of variable x for example you can increase, decrease x value :

*px += 10;
printf("value of x is %d\n",x);
*px -= 5;
printf("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:

int c = 10;
int c2 = 20;

/* define a pointer and points to an constant integer.
pc can point to another integer but you cannot change the 
content of it */

const int *pc = &c;

/* pc++; */ /* cause error */

printf("value of pc is %d\n",pc);

pc = &c2;

printf("value of pc is %d\n",pc);

/* define a constant pointer and points to an integer. 
py only can point to y and its memory address cannot be changed
you can change its content */

int y = 10;
int y2 = 20;

int const *py = &y;

*py++;/* it is ok */
printf("value of y is %d\n",y);

/* 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
Advertisements

Bình luận

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất / Thay đổi )

Connecting to %s