C Pointers With Examples

Pointers are special variables that are used to store addresses rather than values.

int* p;

Assigning addresses to Pointers :

int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc);   // Output: 5

Here, the address of c is assigned to the pc pointer. To get the value stored in that address, here used *pc.

Example:

#include <stdio.h>
int main()
{
   int* pc, c;
   
   c = 22;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c);  // 22
   
   pc = &c;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 22
   
   c = 11;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 11
   
   *pc = 2;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c); // 2
   return 0;
}

Output :

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784
Content of pointer pc: 22

Address of pointer pc: 2686784
Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Explanation of the program:

pc = &c; This assigns the address of variable c to the pointer pc. *pc = 2; This change the value at the memory location pointed by pointer pc to 2.

Common mistakes :

int c, *pc;

// pc is address but c is not
pc = c; // Error

// &c is address but *pc is not
*pc = &c; // Error

// both &c and pc are addresses
pc = &c;

// both c and *pc values 
*pc = c;

To avoid this confusion, we can use this statement :

int* p = &c;

Leave a Comment