C - Get to know Pointer

What is a pointer in C?

A pointer is a variable that contains a memory location.

A pointer is a type of variable. It must be declared in the code and it must be initialized before it's used.

The declaration of a pointer has the following format:

type *name; 

The type identifies the pointer as a char, int, float, and so on.

The name is the pointer variable's name, which must be unique.

The asterisk identifies the variable as a pointer, not as a regular variable.

The following line declares a char pointer, char_pointer:

char *char_pointer; 

And this line creates a double pointer:

double *rainbow; 

To initialize a pointer, you must set its value to the memory location.

That location cannot be a random spot in memory, it must be the address of another variable within the program. For example:

char_pointer = &my_char; 

The preceding statement initializes the char_pointer variable to the address of the my_char variable.

Both variables are char types. After that statement is executed, the char_pointer pointer contains the address of the my_char variable.

The following code shows that that the pointer char_pointer contains the address, or memory location, of variable my_char.

Demo

#include <stdio.h> 

int main() /*from  w ww . j a  va  2 s. co m*/
{ 
   char my_char; 
   char *char_pointer; 

   my_char = 'A';            /* initialize char variable */ 
   char_pointer = &my_char;  /* initialize pointer IMPORTANT! */ 

   printf("About variable 'my_char':\n"); 
   printf("Size\t\t%ld\n",sizeof(my_char)); 
   printf("Contents\t%c\n",my_char); 
   printf("Location\t%p\n",&my_char); 
   printf("And variable 'char_pointer':\n"); 
   printf("Contents\t%p\n",char_pointer); 

   return(0); 
}

Result

The contents of pointer char_pointer are equal to the memory location of variable my_char.

Related Topic