C initialization of pointer



In Previous chapter we have learnt about declaring pointer variable in C Programming. In this chapter we will be looking one step forward to initialize pointer variable in C.

Must Read : Address Operator in C programming

How to Initialize Pointer in C Programming ?

pointer = &variable;

Above is the syntax for initializing pointer variable in C.

Initialization of Pointer can be done using following 4 Steps :

[box]

  1. Declare a Pointer Variable and Note down the Data Type.
  2. Declare another Variable with Same Data Type as that of Pointer Variable.
  3. Initialize Ordinary Variable and assign some value to it.
  4. Now Initialize pointer by assigning the address of ordinary variable to pointer variable.

[/box]
below example will clearly explain the initialization of Pointer Variable.

#include<stdio.h>
int main()
{

int a;       // Step 1
int *ptr;    // Step 2
a = 10;      // Step 3
ptr = &a;    // Step 4

return(0);
}

Explanation of Above Program :

  • Pointer should not be used before initialization.
  • “ptr” is pointer variable used to store the address of the variable.
  • Stores address of the variable ‘a’ .
  • Now “ptr” will contain the address of the variable “a” .

Note :

[box]Pointers are always initialized before using it in the program[/box]

Example : Initializing Integer Pointer

#include<stdio.h>
int main()
{
int a = 10;
int *ptr;

ptr = &a;
printf("\nValue of ptr : %u",ptr);

return(0);
}

Output :

Value of ptr : 4001

In the next chapter we will be learning De-referencing of the pointer variable.