Learn Various Aspects of Pointers in C Programming

In this C language series, you have learned about various components that make up the C programming language. Another important component of the C language is its function to use pointers. What are the pointers?

Whenever we declare a variable in the C language, we are allocating memory space to that variable to store some value. The name of the variable is the name of that allocated memory space.

Now pointers in C Programming also act like some special variables. But rather than storing values, they store addresses. This address is the address of some other variable.

Also read: Learn Various Aspects of String in C Programming

So basically, a pointer points to the address of another variable. This will all clear up with the help of an example. First, let us take a look at the syntax of the Pointer in C Programming.

How to Declare C Pointer

To declare pointers, use the below syntax:

DataType *NameofPointer;

For instance,

int* x;

Here, x is a pointer variable of an integer data type.

How to Initialize pointers in C Programming?

Initializing a pointer variable in C is rather easy. What you have to do is declare a pointer variable of a particular data type. Now declare another variable but keep in mind that its data type should be the same as the pointer variable you declared previously.

Now initialize this ordinary variable by assigning any value to it. The pointer variable will then be initialized by assigning the ordinary variable’s address to the pointer variable.

Pointers in C Programming

Initialization of pointer variable can be further explained with the help of an example:

#include<stdio.h>

int main()

{

int x=01; //Declaration of Variable x;

int *ptr; //Declaration of Pointer Variable ptr

ptr=&x; //Initialize pointer variable with the address of variable ‘x’.

return 0;

}

How to Increment and Decrement Pointers in C?

Just like operations can be performed on ordinary variables, they can be performed on pointer variables too. The increment (++) and decrement (–) operators can be used with pointer variables, but they function differently as compared to ordinary variables.

Pointers in C Programming

When an increment operator is used on a pointer variable, it causes the pointer variable to point to a memory location that is a few bytes ahead of the original memory location.

Similarly, when a decrement operator is used on a pointer variable, it causes the pointer variable to point to a memory location that is a few bytes behind the original memory location.

For Instance, 

#include <stdio.h>

int main()

{

int arr1[6] = {5, 15, 25, 35, 45, 55};

int *ptr, n; //Declare Pointer variable *ptr and ordinary variable n;

ptr=&arr1[0];

n=0;

printf(“Pointers Accessed Array Elements: \n”);

while(n<6)

{

printf(“arr1[%d]=%d \n”,n,*ptr);

ptr++;

n++;

}

return 0;

}

Output

Now the array elements will accessed by pointers:

arr1[0]=5

arr1[1]=15

arr1[2]=25

arr1[3]=35

arr1[4]=45

arr1[5]=55

How to Compare Two Pointers in C? 

Pointer comparison makes sense as long as the two pointers in C Programming point to the same array.

Also Read: Compare Two strings without using Strcmp in C

For instance, 

#include<stdio.h>

int main()

{

int *ptr1,*ptr2; //Declaration of pointers

ptr1=(int *)55;

ptr2=(int *)65;

if(ptr2>ptr1)

printf(“Ptr2 and Ptr1 are far.\n”);

else

printf(“Not far.\n”);

return(0);

}

Output

Ptr2 and Ptr1 are far.

In the above code, two-pointer variables pointing towards different memory locations were compared. Through the comparison, we decided to print (“Ptr2 and Ptr1 are far”) if both of them pointed to different memory locations.

Now, let us take a look at another comparison between two pointer variables having different data types.

For Instance, 

#include<stdio.h>

int main()

{

int *ptra;

float *ptrb;

ptra = (int *)55;

ptrb = (float *)65;

if(ptrb>ptra)

printf(“Both the pointers are far from each other.\n”);

return(0);

}

Output

Both the pointers are far from each other.

Is It Possible to Add or Subtract Some Value to The Pointer? 

Pointer variables support operations like addition and subtraction but they work differently than they do with ordinary variables.

Just like pointer incrementation is an equivalent of ptr=ptr+1, pointer addition and subtraction can be carried out. When we add value to a pointer, say x, then the pointer will point towards a memory location which is x*n bytes ahead of the original memory location. Let us take an example,

#include <stdio.h>

int main()

{

int arr1[6] = {15, 25, 35, 45, 55, 65};

int *ptra, n;

ptra=&arr1[0];

n=0;

printf(“The array elements wil be accessed with pointers.\n”);

while(n<6)

{

printf(“arr1[%d]=%d. \n”,n,*(ptra+n));

n++;

}

return 0;

}

Output

The array elements wil be accessed with pointers.

arr1[0]=15.

arr1[1]=25.

arr1[2]=35.

arr1[3]=45.

arr1[4]=55.

arr1[5]=65.

How to Calculate Size of Pointer in C? 

The below code explains the calculation of the size of pointers in c.

#include<stdio.h>

int main()

{

int *ptra=NULL;

float *ptrb=NULL;

printf(“Size of pointer variable of type integer is : %d bytes. \n”,sizeof(ptra));

printf(“Size of pointer of variable of type float : %d bytes.”,sizeof(ptrb));

return 0;

}

Output

The size of the pointer variable of type integer is : 8 bytes.

Size of the pointer of the variable of type float: 8 bytes.

Does the Size of Pointer Depend on Compiler?

The size of the pointer does not depend on the compiler, but it depends on the architecture of the machine you are using. For instance, if your system is 32-bit, then the size of the pointer will be 4 bytes, but for a 64-bit system, the size of the pointer becomes 8 bytes.

Accessing Array Elements Using Pointer in C

Yes, array elements can be accessed by the use of pointers in C Programming, and the sample code is provided below.

#include <stdio.h>

int main()

{

int arr1[6];

printf(“Enter the array elements: \n”);

for(int x=0;x<6;++x)

scanf(“%d”, arr1 + x);

printf(“The entered elements are: \n”);

for (int x=0;x<5;++x)

printf(“%d\n”,*(arr1+x));

return 0;

}

Output

Enter the array elements:

1

2

5

6

7

9

The entered elements are:

1

2

5

6

7

Accessing String Using Pointers 

Yes, strings can be accessed using pointers in C programming. The below-given sample code explains how this is done. But, if you don’t have knowledge about strings in C. Then, first practiced strings in C.

#include <stdio.h>

int main(void)

{

char strng[5]=”Hey!”;

char *ptra=strng;

while(*ptra!=’\0′)

{

printf(“%c”,*ptra);

ptra++;

}

return 0;

}

Output

Hey!

Difference Between %x and %p Format Specifier 

Format specifiers are used to specifying the type of data that will be printed to the screen by the printf function. So %x serves as the format specifier for hexadecimal numbers while %p serves as the format specifier for pointer variables. But both of these ultimately print the address.

For Instance, 

#include<stdio.h>
int main()
{
int x=5;
int *ptr=&x;
printf(“%p\n”,ptr);
printf(“%x\n”,ptr);
}

Output

0x7fffe1cdc9d4

e1cdc9d4

Common Mistakes in Pointers in C Programming

Some of the mistakes that most programmers do.

Omitting Pointer

int *ptra,ptrb;

In the above line of code, pointers *ptra and ptrb of type integer have been declared. But if you notice, ptrb is declared just as an ordinary variable and not pointer variable. So, you should write this line in program like,

int *ptra, *ptrb;

Uninitialized Pointer

This happens when a valid address is not being assigned by the programmer to a pointer before the pointer is brought into usage.

#include <stdio.h>

int main()

{

int *ptr;//Declare Pointer ‘ptr’

*ptr=20;//Assigning value to the pointer ‘ptr’

printf (“Value %d\n”, *ptr);

return 0;

}

Comparison of Pointers in C

This happens when two pointers that point to different arrays are being compared.

#include <stdio.h>

#include <string.h>

int main()

{

char str[7]=”WORLD”;

char str1[7]=”HELLO”;

char *ptr1,*ptr2;

ptr1=str;

ptr2=str1;

if (ptr1>ptr2)

{

//required statement

}

return 0;

}

Ilegal Indirection

While declaring pointers in C programming, the value used by pointers should always be kept in mind. Example: using malloc() function

*int ptr = malloc(sizeof(int)); //This is an invalid statement

The above statement is incorrect. The correct method to allocate memory is,

int ptr=malloc(sizeof(int)); //This is the valid statement

Pointer Pointing Invalid Address

If the pointer points to invalid memory location, compiler gives a run-time error.

#include <stdio.h>

#include <stdlib.h>

int main()

{

int *ptr; //Declare pointer variable ‘ptr’

free(ptr); // Free the allocated address

*ptr=30; //Assigning value to the pointer ‘ptr’

printf(“Value %d\n”,*ptr);

return 0;

}

Types of Pointers in C Programming

Types of Pointers in C are:

  1. Null Pointer in C
  2. Wild Pointer in C
  3. Void Pointer in C/Generic Pointer
  4. Dangling Pointer in C
  5. Double Pointer in C

What is Null Pointer in C? 

In simple words, a null pointer can be defined as a pointer that does not point to any memory location. A null pointer just stores the base address. The data type of a null pointer is void, and store a Null value.

What Null means is that the pointer is pointing to the 0th memory location. The Null value is defined in a header file called stddef.

Syntax of Null Pointer 

<data type> *<Variable_Name> = NULL;

For instance, int*p = NULL;

In the above example, pointer p is an integer type pointer variable which is initialized with NULL and pointer *p is known as a NULL pointer.

For Instance, 

int *ptr=(int *)0;
float *ptr=(float *)0;
char *ptr=(char *)0;

Now let us take a look at a sample program to understand the use of Null pointers better.

First, let us take a look at the below-given code:

#include <stdio.h>

int main()

{

int *ptr;

printf(“Address of the variable is: %d”, ptr);

printf(“Value of the variable is: %d”, *ptr);

return 0;

}

When you run the above code, the program will crash or will a compile-time error. It is expected that the compiler will return a garbage value, but that does not happen because the pointer is not initialized and points to no address. So it is very harmful to keep an uninitialized pointer in a code. Now, how do we solve this problem? For that, let us take a look at another code.

#include <stdio.h>

int main()

{

int *ptr=NULL;

if(ptr!=NULL)

{

printf(“The pointer variable value is: %d\n”,*ptr);

}

else

{

printf(“The pointer is not valid.\n”);

}

return 0;

}

Output

The pointer is not valid.

So this is how you solve the problem of an uninitialized pointer. You use conditional statements if and else. If the program does contain a null pointer, let the program print out the pointer value, else, print something like “Invalid Pointer” to let the user know about it.

Some Points to Remember 

This is considered good practice if you assign a null value to pointer variables. When you don’t have a valid address to assign to the pointer variables then you can use NULL. A pointer that is initialized with NULL value is known as a NULL pointer in C.

A NULL pointer is a predefined macro and its value is 0 which defined in the ‘stdio.h’, ‘alloc.h’, ‘stdlib.h’, ‘mem.h’, ‘stddef.h’ header files.

What is Void Pointer in C? 

When we assign an address to a pointer, the address should be the same as the variable type which was specified while declaring a pointer. So an int type pointer will point to an int type variable, not a float or char type variables. Void pointer is used to avoid this situation. Void Pointer also is known as a generic pointer.

So a void pointer can be defined as a pointer that can point to a variable of any data type.

Syntax of Void Pointer in C 

void *ptr_name;

Example: void *ptr;

How to Find out Size of Void Pointer in C

The size of a void pointer is generally the same as the size of the char pointer. But the size generally varies from system to system. It can be different in our system and different on yours.

Let us take a look at a sample code to find the size of void pointers.

#include <stdio.h>

int main()

{

void *ptra = NULL;

int *ptrb = NULL;

char *ptrc = NULL;

float *ptrd = NULL;

printf(“The size of void pointer is: %d\n”,sizeof(ptra));

//Print Sizeof pointer ptrb

printf(“Size of integer pointer is: %d\n”,sizeof(ptrb));

//Print Size of pointer ptrc

printf(“The size of character pointer is: %d\n”,sizeof(ptrc));

//Pointer Size of Pointer ptrd

printf(“Size of float pointer is: %d\n”,sizeof(ptrd));

return 0;

}

Output

The size of void pointer is: 8

Size of integer pointer is: 8

The size of character pointer is: 8

Size of float pointer is: 8

Dereferencing of a Void Pointer 

A void pointer cannot be dereferenced. This can be understood using a program.

#include<stdio.h>

int main()

{

int x = 25;

void *ptra = &x;

printf(“%d”, *ptra);

return 0;

}

Output

The compiler will show a compile-time error. This is because void is not a pointer to object type.

Arithmetic Operation on Void Pointer in C 

Arithmetic operations cannot be performed on void pointers in C. This is set according to the C standard. This can be understood using a program.

#include<stdio.h>

int main()

{

int x[3] = {2, 4, 6};

void *ptra = &x;

ptra = ptra + sizeof(int);

printf(“%d”, *(int *)ptra);

return 0;

}

Output

4

Use of Void Pointers in C Programming

Void pointers in C programming are highly reusable and can be used for multiple variables belonging to different data types. This can make the programs easier to write, hence void pointers are used in C.

For Instance, 

#include<stdio.h>

int main()

{

int x=25;

float y=7.5;

char z=’x’;

void *ptra;

ptra=&x;

printf(“The value of x is: %d\n”,*((int*)ptra));

ptra=&y;

printf(“The value of y is: %f\n”,*((float*)ptra));

ptra=&z;

printf(“The value of z is: %c\n”,*((char*)ptra));

return 0;

}

Output

The value of x is: 25

Value of y is: 7.500000

The value of z is: x

In the above code, we have used the same pointer multiple times so there was no need to declare a new pointer.

Application of Void Pointer in C 

A memory of any data type can be allocated using malloc() and calloc() because they return void* type. Take a look at this code snippet to understand this.

#include<stdio.h>

int main(void)

{

int *x = malloc(sizeof(int) * n);

}

What is Wild Pointer in C? 

Wild pointers in C programming are those pointers that have not been initialized. They point to an arbitrary location and create trouble in the program by making it crash.

Examples of Wild Pointer Generation 

int main()

{

int *ptra;

*ptra = 12;

}

Here, *ptra is a wild pointer.

int main()

{

int  *ptra;

int x = 25;

ptra = &x;

*ptra = 50;

}

How to Avoid Wild Pointers in C ? 

It is required that you always initialize a pointer to avoid situations where a program might crash. But if you want a pointer to a value without declaring a variable for that value, then you will have to explicitly allocate some memory to put that value in.

This can be understood by this code snippet.

int main()

{

int *ptra = (int *)malloc(sizeof(int));

*ptr = 25;

}

Hello, My Name is Abhinav. I am an Author in the Education Category of Trickyedu. I have Done My Engineering in Computer Science from DIT University. I have a good command on Science, Programming Language, and microprocessors. So, I choose this platform to share my knowledge and experience.

Leave a Comment