Displaying memory address and the stored value for pointer variable in C programming

 

 

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: Displaying memory address and the stored value for pointer variable in C programming

To show: The basic of pointer use demonstrating the memory address and the actual location of the stored variable data

 

 

// The basic pointer use

#include <stdio.h>

#include <stdlib.h>

 

void main(void)

{

// Declare and initialize an int variable

int var = 34;

// Declare a pointer to int variable

int *ptr;

// Initialize ptr to point to variable var

ptr = &var;

 

// Access var directly and indirectly

printf("\nDirect access, variable var value = var = %d", var);

// you can use %p for the pointer memory address directly or

// %0x or %0X or %p in hexadecimal representative instead of

// %d, just to avoid confusion here

printf("\nIndirect access, variable var value = *ptr = %d", *ptr);

// Display the address of var two ways

printf("\n\nThe memory address of variable var = &var = %p", &var);

printf("\nThe memory address of variable var = ptr = %p\n", ptr);

}

 

Output example:

 

Direct access, variable var value = var = 34

Indirect access, variable var value = *ptr = 34

The memory address of variable var = &var = 0012FF60

The memory address of variable var = ptr = 0012FF60

Press any key to continue . . .

 

 

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