Introduction to Pointers
Understand pointers with the help of a simple example.
We'll cover the following
Pointers
Pointers are like any other variables. Their specialty, however, is storing addresses of other variables.
Pointer declaration
The basic syntax for declaring a pointer is given below:
dataType * variableName;
Example program
Let’s understand pointers with the help of a simple example. Press the RUN button and see the output!
# include <stdio.h>int main( ){// Initializes variable iint i = 3 ;// Declares pointer jint *j ;// Stores the address of i in jj = &i ;// Prints address of iprintf ( "Address of i = %u\n", &i ) ;printf ( "Address of i = %u\n", j ) ;// Prints address of jprintf ( "Address of j = %u\n", &j ) ;// Prints value of iprintf ( "Value of i = %d\n", i ) ;printf ( "Value of i = %d\n", *( &i ) ) ;printf ( "Value of i = %d\n", **&j) ;printf ( "Value of i = %d\n", *j ) ;// Prints value of jprintf ( "Value of j = %u\n", j ) ;printf ( "Value of j = %u\n", *&j) ;return 0 ;}
Explanation
Lines 7-9: the difference between an integer and an address
An address permits limited arithmetic, i.e., pointer + number
, pointer - number
, and pointer - pointer
. All other arithmetic is not permitted. This will be further explained later in the course.
-
int *j
means the value at the address stored inj
is an integer. This declaration informs the compiler thatj
will store an address of an integer, not an integer itself, soj
is defined to be of the typeint *
. -
j = &i
means we are storing the address of variablei
inj
, i.e., 4096;j
itself might be given the location, 4160, or any such location.
Lines 12-13: We can get the address of i
through the expressions: j
or &i
.
Line 15: We can get the address of j
through the expression: &j
.
Lines 19-22: The value of i
can be printed using the expressions: i
, *&i
, *j
, and **&j
.
Lines 24-25: To get the value of j
, we can either use j
or *&j
.
📝 Note: Since
j
is the same as*&j
, in the expression:*j
;j
can be replaced with*&j
, resulting in the expression:**&j
. Moreover,*&j
is same as*(&j)
.
Pointers store whole numbers
See the output of the code given below!
#include<stdio.h>int main() {// Initializes variable ch and fchar ch = 'a';float f = 1.5;// l stores an address of char variablechar *l;l = &ch;// m stores an address of float variablefloat *m;m = &f;// Prints address of l and mprintf ( "Value of l = %u\n", l ) ;printf ( "Value of m = %u\n", m ) ;return 0;}
In the code above, l
and m
are pointer variables, and they will store whole numbers. Keep in mind that addresses are whole numbers; therefore, pointers always store whole numbers.
Line 8: char *l
informs the compiler that l
will store an address of a char value, not the char value itself.
Line 11: Similarly, float *m
informs the compiler that m
will store an address of a floating-point value, not the floating-point value itself.