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 :
- Declare a Pointer Variable and Note down the Data Type.
- Declare another Variable with Same Data Type as that of Pointer Variable.
- Initialize Ordinary Variable and assign some value to it.
- Now Initialize pointer by assigning the address of ordinary variable to 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 :
Pointers are always initialized before using it in the program
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.