You are on page 1of 29

POINTERS

IN
C Programming
What are Pointers?

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 −

type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the
name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk
used for multiplication. However, in this statement the asterisk is being used to designate
a variable as a pointer. Take a look at some of the valid pointer declarations −

 int *ip; /* pointer to an integer */


 double *dp; /* pointer to a double */
 float *fp; /* pointer to a float */
 char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the
variable or constant that the pointer points to.
How to Use Pointers?
There are a few important operations, which we will do with the help of pointers very
frequently. 
(a) We define a pointer variable, 
(b) assign the address of a variable to a pointer
(c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at
the address specified by its operand.
Declaring a pointer
The pointer in c language can be declared using *
(asterisk symbol). It is also known as indirection pointer
used to dereference a pointer.

int *a; //pointer to int  
char *c; //pointer to char  
#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var ); /* address stored in
pointer variable */
printf("Address stored in ip variable: %x\n", ip ); /* access the value
using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
Output

Address of var variable: bffd8b3c


Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
Advantage of pointer
1) Pointer reduces the code and improves the
performance, it is used to retrieving strings, trees, etc. and
used with arrays, structures, and functions.
2) We can return multiple values from a function using
the pointer.
3) It makes you able to access any memory location in the
computer's memory.
Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc()
functions where the pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It
reduces the code and improves the performance.
Arrays and Pointers
 Arrays and pointers are closely related in C. In fact an array declared as
int A[10];
 can be accessed using its pointer representation.
 The name of the array A is a constant pointer to the first element of the array.
 So A can be considered a const int*.
 Since A is a constant pointer, A = NULL would be an illegal statement.
 Arrays and pointers are synonymous in terms of how they use to access memory.
 The important difference between them is that, a pointer variable can take different
addresses as value whereas, in case of array it is fixed.
Array of pointer
Let's create an array of 5 pointers.
int *arr[5];
Where arr[0] will hold one integer variable address, arr[1] will hold another
integer variable address and so on.
Example

#include<stdio.h>
#define size 5 printf("Address of a = %p\n",arr[0]);
printf("Address of b = %p\n",arr[1]);
int main() printf("Address of c = %p\n",arr[2]);
{ printf("Address of d = %p\n",arr[3]);
int *arr[size]; printf("Address of e = %p\n",arr[4]);
int a = 10, b = 20, c = 30, d = 40, e = 50, i;
for(i = 0; i < size; i++)
arr[0] = &a; printf("value stored at arr[%d] = %d\
arr[1] = &b; n",i,*arr[i]);
arr[2] = &c;
arr[3] = &d; return 0;
arr[4] = &e; }
Output
Address of a = 0x7fff959067b8
Address of b = 0x7fff959067bc
Address of c = 0x7fff959067c0
Address of d = 0x7fff959067c4
Address of e = 0x7fff959067c8
value stored at arr[0] = 10
value stored at arr[1] = 20
value stored at arr[2] = 30
value stored at arr[3] = 40
value stored at arr[4] = 50
Pointer Array
A pointer is a place in memory that keeps address of An array is a single, pre allocated chunk of contiguous
another place inside elements (all of the same type), fixed
in size and location.

Allows us to indirectly access variables. In other


Expression a[4] refers to the 5th element of the array
words, we can talk about its address rather than its
a.
value
Array can be initialized at definition. Example
Pointer can’t be initialized at definition  
int num[] = { 2, 4, 5}
They are static in nature. Once memory is
Pointer is dynamic in nature. The memory
allocated , it cannot be resized or freed
allocation can be resized or freed later.
dynamically
C - Pointers and Strings
Creating a string
we are creating a string str using char character array of size 6.
char str[6] = "Hello";
The above string can be represented in memory as follows.

              

Each character in the string str takes 1 byte of memory space.


Creating a pointer for the string
The variable name of the string str holds the address of the first element of the array i.e., it points
at the starting memory address.
So, we can create a character pointer ptr and store the address of the string str variable in it. This
way, ptr will point at the string str.

In the following code we are assigning the address of the string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.
        
The pointer variable ptr is allocated memory address 8000 and it holds the address of
the string variable str i.e., 1000.
Accessing string via pointer
 To access and print the elements of the string we can use a loop and check for the \0 null
character.
 In the following example we are using while loop to print the characters of the string
variable str.
#include <stdio.h> // print the string
while(*ptr != '\0') {
int main(void) { printf("%c", *ptr);

// string variable // move the ptr pointer to the next


char str[6] = "Hello"; memory location
ptr++;
// pointer variable }
char *ptr = str;
return 0;
}
Using pointer to store string
We can achieve the same result by creating a character pointer that points at a string value stored
at some memory location.
In the following example we are using character pointer variable strPtr to store string value.

#include <stdio.h> // print the string


while(*t != '\0') {
int main(void) { printf("%c", *t);

// pointer variable to store string // move the t pointer to the next


char *strPtr = "Hello"; memory location
t++;
// temporary pointer variable }
char *t = strPtr;
return 0;
}
In the above code we are using another character pointer t to print the characters of the string as
because we don't want to lose the starting address of the string "Hello" which is saved in pointer
variable strPtr.

In the above image the string "Hello" is saved in the memory location 5000 to 5005.
The pointer variable strPtr is at memory location 8000 and is pointing at the string address 5000.
An Array of Pointers in C
What is an Array?
If we want to include multiple elements in a program with the very same data type, we can use an
array. Let us assume that we are using a total of five integers in any program. There are two different
ways in which we can allocate memory to all of these integers:
• We can create five integers differently;
• We can create an array of all the different integers.
One of the huge advantages of using arrays is that it becomes very easy for a programmer to access all
the elements in the program easily. All the elements can be accessed in a single run of a loop in the
program.
What is a Pointer?
The pointers in C point towards the variables present in a program. They hold the addresses
of the variables. The program will use these addresses to access the variables and modify
them. Here are the three crucial things that come into play when dealing with pointers in C:

• Declaration of the pointer variable


• Initialisation of the pointer variable
• Using the pointer to access the variable
What is an Array of Pointers in C?
 When we want to point at multiple variables or memories of the same data type in a C program,
we use an array of pointers.
 Let us assume that a total of five employees are working at a cheesecake factory. We can store
the employees’ names in the form of an array. Along with this, we also store the names of
employees working at the office, the library, and the shoe store.
 Now, let us assume that once we read all the names of the employees randomly, we want to sort
all of the employees’ names working in the cheesecake factory.
 Sorting all the employee names requires reading, swapping, and copying a lot of data. But since
we have stored all the employee names in groups/ arrays, we can directly refer to the array of
names of employees working at the cheesecake factory.
The Application of Arrays of Pointers
Let us assume that we want to build an enclosed system, and this system uses a different kind of
thermometer for measuring the temperature. Now, in this case, we can use an array for holding the
address of memory for every sensor. This way, manipulation of the sensor status becomes very easy.
Example
The thermo[0] will be holding the 1st sensor’s address.
The thermo[1] will be holding the 2nd sensor’s address and so on.
Now, since it’s an array, it can interact directly with the thermo pointer indexed in the array. Thus, we
will get the 1st sensor’s status with the thermo[0], the second one using the thermo[1], and so on
ahead.
Declaration of an Array of Pointers in C
An array of pointers can be declared just like we declare the arrays of char, float, int, etc. The
syntax for declaring an array of pointers would be:
data_type *name_of_array [array_size];
Now, let us take a look at an example for the same,
int *ary[55]
This one is an array of a total of 55 pointers. In simple words, this array is capable of holding
the addresses a total of 55 integer variables. Think of it like this- the ary[0] will hold the
address of one integer variable, then the ary[1] will hold the address of the other integer
variable, and so on.
Example
#include<stdio.h>
#define SIZE 10
int main()
{
int *arr[3];
int p = 40, q = 60, r = 90, i;
arr[0] = &p;
arr[1] = &q;
arr[2] = &r;
for(i = 0; i < 3; i++)
{
printf(“For the Address = %d\t the Value would be = %d\n”, arr[i], *arr[i]);
}
return 0;
}
The output generated out of the program mentioned above would be like this:
For the Address = 387130656 the Value would be = 40
For the Address = 387130660 the Value would be = 60
For the Address = 387130664 the Value would be = 90
How Does it Work?
Take a look at how we assigned the addresses of the pointers p, q, and r. We first assign the p variable’s
address to the 0th element present in the array. In a similar manner, the 1st and 2nd elements of the
array will be assigned with the addresses of q and r. At this very point, the array, arr would look like
this:
Pointers as Function Argument in C
Pointer as a function parameter is used to hold addresses of arguments passed during
function call. This is also known as call by reference. When a function is called by
reference any change made to the reference variable will effect the original variable.

You might also like