C Pointers
C Pointers
Some C programming tasks are performed more easily with pointers, and other tasks, such as
dynamic memory allocation, cannot be performed without using pointers.
Uses of Pointers?
a) To create dynamic data structure
b) To pass and handle variable parameters passed to functions
c) To access information stored in arrays
d) To avoid wastage of memory
Pointer Declaration
Every pointer starts with a *. The general form of a pointer variable declaration is :
type *var-name;
e.g #include<stdio.h>
int main()
{
int x;
int *ptr; /* declare a pointer*/
x=5; /* initialise x */
ptr=&x; /* assign to ptr the address of x */
return 0;
}
b) To access the value of the interger that is being pointed to, you have to dereference the pointer by using the
*
e.g #include<stdio.h>
int main()
{
int x, y;
int *ptr;
x=5;
ptr=&x;
y=*ptr; /* dereference the pointer */
printf("%d\n", y);
return 0;
}
int main () {
return 0;
}
NULL Pointers
A pointer that is assigned NULL is called a nullpointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
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 */
POINTER TO POINTER
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains the
actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, the following declaration declares a
pointer to a pointer of type int −
int **var;
example
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Tutorial
By using C comments, indicate the output or what happens at the end of each code statement.
1. int a;
int *ptr;
a=42;
ptr=&a;
printf("%d", *ptr);
*ptr=56;