C/C++ pointers

Pointers in C/C++ can sometimes be really confusing specially if you are a beginner or like me more used to Java. Here is a small program I found really useful in understanding c pointers:

#include <stdio.h>
int main() {
   int int_var = 5;
   int *int_ptr;

   int_ptr = &int_var; // Put the address of int_var into int_ptr.

   printf("int_ptr = 0x%08x\n", int_ptr);
   printf("&int_ptr = 0x%08x\n", &int_ptr);
   printf("*int_ptr = 0x%08x\n\n", *int_ptr);

   printf("int_var is located at 0x%08x and contains %d\n", &int_var, int_var);
   printf("int_ptr is located at 0x%08x, contains 0x%08x, and points to %d\n\n",
      &int_ptr, int_ptr, *int_ptr);
}

If you compile and run the code you will get something similar to the following:

int_ptr = 0xbffff834
&int_ptr = 0xbffff830
*int_ptr = 0x00000005

int_var is located at 0xbffff834 and contains 5
int_ptr is located at 0xbffff830, contains 0xbffff834, and points to 5

The address of your variables are probably different from what I have here which is obvious. One thing you should pay attention to is the relationship between the value/address of the pointer and the address of the int variable.

Leave a Reply

Anti-Spam Protection by WP-SpamFree