Pointer in C Programming
Pointers:
variable declaration var1 and var2 (array declaration) . And now we are printing address of both these
variable.
#include <stdio.h>
char var2[10];
printf("Address of var2 variable: %x\n", &var2 );
}
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
A pointer is
a variable whose value is the address of another variable, i.e., direct address
of the memory location.
Like any variable or
constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is –
<datatype>
*<variablename>
Eg.
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
-----------------------------------------------------------------------------------------------------------------
example.
int *p;
int a = 10;
p = a;
[p will store the address of a ]
How
to Use Pointers?
#include <stdio.h>
int *p; /* pointer variable declaration */
printf("Address stored in p variable: %x\n", p );
printf("Value of *p variable: %d\n", *p );
}
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
Example 2:
#include <stdio.h>
#include <conio.h>
int *p; /* pointer variable declaration */
printf(“%d”,p); //2046
printf(“%d”,&i); //2046
printf(“%d”,&p); //3002
printf(“%d”,*p); //100
printf(“%d”,*(&i)); //100
}
NULL
Pointers
It is always a good
practice to assign a NULL value to a pointer variable in case you do not have
an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
#include <stdio.h>
#include <conio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
The value of ptr is 0
How to check Null Pointer Condition:
To check for a null
pointer, you can use an 'if' statement as follows −
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
No comments:
Post a Comment