C and C++ Pointers


Click here to change the theme.

The following table is some sample C code and a conceptual view of what the data might look like in memory in a 32-bit Windows environment. As you can see later below, the actual contents are a bit different. Notice that the memory location increases by four for each item since both integer items and pointers are 4 bytes in 32-bit Windows environments.

 

Memory Contents

Sample Code Location Data
int Number = 0x555141; 1004 0x555141
int *pNumber = &Number; 1008 1004
int n = *pNumber; 100C 0x555141

The following is a little program that shows this:

#include <iostream.h>
#include <stdlib.h>

void ShowMemory(int *p) {
    char s[16];
cout << (void *)p << " 0x0" << _itoa(*p, s, 16) << endl;
}

int main(int argc, char *argv[], char *envp[]) {
    int Number = 0x555141;
    int *pNumber = &Number;
    int n = *pNumber;
ShowMemory(&Number);
ShowMemory((int *)&pNumber);
ShowMemory(&n);
return 0;
}

The following is sample actual output of the program above, as compiled by the Visual C++ compiler. Note that the memory locations will likely be different for you if you compile and run this program.

0012FF68 0x0555141
0012FF6C 0x012ff68
0012FF64 0x0555141