Pointers

Pointer v.s. Pointer Variable

A pointer is a variable stores the address of variables or a memory location.

A pointer variable is a variable that it's value is the address of another variable.

int a = 5; // address of a is 0x4CFF00
int b = 10;
int *p = &a; // address of p is 0x4CFF79
printf("*p = %d\n", *p); // output: *p = 5
printf("p = 0x%x\n", p); // output: p = 0x4CFF00
printf("&p = 0x%x\n", &p); // output: &p = 0x4CFF79
What is the output in the following ?

int main() {
	int a = 5;
	int *p = &a;
	printf("*p = %d\n", *p);
	*p = 10;
	printf("a = %d\n", a);
}
*p = 5;
a = 10;

What is the output in the following ?

int main() {
	int a = 5; // address of a is 0x4CDE00;
	int b = 10; // address of b is 0x4CDE04;
	int *p = &a; // address of p is 0x4CDE80;
	printf("*p is %d\n", *p);
	printtf("p is 0x%x\n", p); 
	printf("&p is 0x%x\n", &p);
	p = &b;
	printf("*p = %d\n", *p);
	printf("p = 0x%x\n", p);
	printf("&p = 0x%x\n", &p);
	return 0;
}

The output are :

*p is 5
p is 0x4CDE00;
&p is 0x4CD80;
*p is 10;
p is 0x4CDE04;
&p is 0x4CD80;
Please point out the error and correct it.

int a = 10;
int *p = NULL;
*p = &a;

*p is the pointer variable which could not store the address of a. So the last line should be modified to:

p = &a;

There's a post on stack overflow summarizes pointer operators[1]

ptr++; // pointer moves to the next int position.
++ptr; // pointer moves to the next int position.

++*ptr;   // the value pointed at the ptr is incremented.
++(*ptr); // the value pointed at the ptr is incremented.
++*(ptr); // the value pointed at the ptr is incremented.
*ptr++; // pointer moves to the next position but return the old content.
(*ptr)++; // the value pointed at by ptr is incremented.
*(ptr)++; // pointer moves to the next int position but return the old content.

Pointer moves to the next int position, and then get's accessed, with your code, segfault.

*++ptr; // pointer moves to the next int position and then get's accessed.
*(++ptr);
Tell the output in the following.

int main() {
	static int x = 5; // address of x is 0xFF4CC010
	static int *p = &x; 
	printf("(int) p => %d\n", (int)p);
	printf("(int) p++ => %d\n", (int)p++);
	printf("(int) ++p => %d\n", (int)++p);
	x = 5; p = &x;
	printf("(int) ++p => %d\n", (int)++p);
}

The output are:

  • (int) p => 0xFF4CC010
  • (int) p++ => 0xFF4CC010
  • (int) ++p => 0xFF4CC018
  • (int) ++p => 0xFF4CC014

  1. https://stackoverflow.com/questions/8208021/how-to-increment-a-pointer-address-and-pointers-value/8208106#8208106 ↩︎