Declaration, Initialization & Accessing of Pointer Variable
Declaration of Pointer Variable
1. int* variable_name;
2. int * variable_name;
3. int *variable_name;
Which style will you choose?
1. If we want to declare only variable not pointer variable in line beside a pointer variable declaration then we can’t do it in style 1 and 2.
int* pointer_variable, normal_variable;
int * pointer_variable, normal_variable;
Both of them have declared two variable as pointer variable but we want to declare first as pointer variable and second as normal variable.
This problem is solved by following the third style.
int *pointer_variable, normal_variable;
Here the statement tells the compiler that first variable is pointer and second is normal variable.
2. Another reason to choose the third style is it is similar to access the value of a pointer variable (we will discuss it later).
So finally we will follow the third style to declare a pointer variable. For that the standard form of declaration of pointer variable is:
For integer type variable: int *pointer_variable;
For float type variable: float *pointer_variable;
For character type variable: char *pointer_variable;
Initialization of Pointer Variable
To initial a pointer variable first we have to declare a variable whom to be pointed by a pointer variable. So the form of initialization of pointer variable is:
data_type variable_name, *pointer_variable;pointer_variable = &variable_name;
We can declare and initial in one statement as the following:
int variable_name, *pointer_variable = &variable;
Now if we want to compile the following statement it will print the address of variable_name.
The most interesting in pointer is it’s flexibility. You can initial one pointer variable to same type different variable as same as below:
int var_one, var_two, *pointer_var;
pointer_var = &var_one;
pointer_var = &var_two;
int variable_name, *pointer_one, *pointer_two;
pointer_one = &variable_name;
pointer_two = &variable_two;
NULL or Zero Pointer
int *pointer_variable = NULL;
int *pointer_variable = 0;
Get The Value Of Pointers / Accessing Variable Through Its Pointer
int n = *pointer_var;
/*VARIABLE AND POINTER DECLARATION*/
int value, *ptr, n;
/*INITIALIZAITON OF VARIABLA VALUE*/
value = 1000;
ptr = &value;
/*ACCESS VALUE FROM POINTER AND ASSIGN TO ANOTHER VARIABLE*/
n = *ptr;
/*PRINT THE RESULT*/
printf(“Value of Pointer: %dn”,n);
var = 80;
printf(“The value of var: %dn”, var);
printf(“The address of var: %un”, &var);
printf(“The value of *(&var): %dn”, *(&var));