A simple C pointer program example demonstrating the memory address and actual data of the variable

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server, Standard Edition

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Differentiate between the memory address and the actual stored data location of the variables in C pointer programming

To show: How to use C pointer properly and differentiate between the memory address and the actual data location of the variables

 

 

#include <stdio.h>

 

// struct declaration

struct Branch

{

int value;

struct Branch *left;

struct Branch *right;

};

 

void main(void)

{

struct Branch x, y, z, *p = &y;

 

printf("&x = %p, &y = %p, &z = %p, p = %p\n", &x, &y, &z, p);

 

x.value = 100;

y.value = 200;

z.value = 300;

x.left = (struct Branch *) 0;

x.right = &z;

z.left = NULL;

z.right = &y;

y.right = &x;

y.right = &z;

 

printf("\n&x = %p: x.value = %d, x.left = %p, x.right = %p\n", &x, x.value, x.left, x.right);

printf("&y = %p: y.value = %d, y.left = %p, y.right = %p\n", &y, y.value, y.left, y.right);

printf("&z = %p: z.value = %d, z.left = %p, z.right = %p\n\n", &z, z.value, z.left, z.right);

printf("&y = %p, y.value = %d \n", &y, y.value);

printf("y.left = %p, y.right = %p \n", y.left, y.right);

printf("p = %p, (*p).value = %d \n", p, (*p).value);

printf("(*p).left = %p, (*p).right = %p\n", (*p).left, (*p).right);

 

p = (*p).left;

 

printf("\np = %p, (*p).value = %d \n", p, (*p).value);

printf("(*p).left = %p, (*p).right = %p\n", (*p).left, (*p).right);

 

p = (*p).right;

 

printf("\np = %p, (*p).value = %d \n", p, (*p).value);

printf("(*p).left = %p, (*p).right = %p\n", (*p).left, (*p).right);

}

 

Output example:

 

&x = 0012FF58, &y = 0012FF44, &z = 0012FF30, p = 0012FF44

 

&x = 0012FF58: x.value = 100, x.left = 00000000, x.right = 0012FF30

&y = 0012FF44: y.value = 200, y.left = CCCCCCCC, y.right = 0012FF30

&z = 0012FF30: z.value = 300, z.left = 00000000, z.right = 0012FF44

 

&y = 0012FF44, y.value = 200

y.left = CCCCCCCC, y.right = 0012FF30

p = 0012FF44, (*p).value = 200

(*p).left = CCCCCCCC, (*p).right = 0012FF30

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index