Pointers in C Programming

The real C programming starts from the day you’re handling Pointers in C Programming. I recommend you to make sure, that you understood previous lessons. Until you’re comfortable with basics, it would be difficult to understand pointers. Pointers provide an indirect method of accessing variables.

Basics of Pointers 

Now the question is how pointer manages to do this? The answer is Pointers are variables that store address of another variable. This is why they are capable to work with memory address. Pointers can also improve efficiency of your programs. They are capable of dynamically allocate memory, which means that you can write programs that can handle unlimited amount of data. Now we have seen many advantages of using pointers. Let’s look at pointer declarations.

int *p;  // pointer 'p' of type integer

Here p is pointer and * is asterisk sign which initialize pointer variable. In this example pointer “pis of type integer.

Example: This program initializes pointer p. The variable of type integer a =10. This program clearly demonstrates the use of pointer.

#include <stdio.h>

int main(){
    int a;
    int *p;
    a = 10;

    p = &a; // &a = address of a

    printf("%d\n", p);
    printf("%d\n", *p); // *p = value at address pointed to 'p'
    printf("%d\n", &a);
}

I recommend you to build and run this code snippet and observe output. The output from this program is:

basic program of pointer
basic program of pointer

int a; statement initializes variable a of type integer. int *p; is nothing but declaration of pointer variable. Here a = 10; assign value i.e. 10 to variable a. p = &a; as discussed earlier pointer is a variable whose value is address of another variable. Here in this case p hold the address of a.

printf(“%d\n”, p); this statement prints the value of p which will be an address of a. Now in this case its 2686744 will be printed on screen. This result may vary from machine to machine. Don’t worry if you get different output. Next statement printf(“%d\n”, *p); will print 10 because p hold address of a and the value assigned to a is 10. This is also been referred as dereferencing a pointer *p. (* basically dereferences the pointer to value).

The final printf(“%d\n”, &a); statement prints address or location of a. Usually & sign is address operator and printing this &a will result 2686744. I recommend you to spend time and make sure you understand everything before you move further. If you’re comfortable with this example then you already got into Pointers in C Programming. Even most experience people sometime confuse with pointers.

There are several types of pointers can be declared in C Programming. The table below will list them with an example:

Types of Pointers Example
Pointer to an integer int    *ip;
Pointer to a float float  *fp;
Pointer to a double double *dp;
Pointer to a character char   *ch;
Void Pointer void *ptr;
NULL Pointer int *ptr=NULL;

NULL Pointer

Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment. Here are some examples:

int *ptr=NULL;
char *ptr=’\0’;
int *ptr=(int *)0;
char *ptr=(char *)0;
float *ptr=(float *)0;
double *ptr=(double *)0;
Example: NULL Pointer in C Programming
#include <stdio.h>

int main()
{
    int *p = NULL;
    printf("The value of p is : %x\n", p);
    return 0;
}

The output of this program prints 0 on screenlearn-embedded-system

Void Pointer

void pointers can be assigned to any pointer value. Void pointer can access and manipulate any kind of variable data properly. When working with void pointer type, specification will be decided at the time of execution. Whenever we use void pointer to access data, its mandatory to use type casting process or else it gives an errors, because type specification need to be decided at the time of execution. Usually void pointer is 2 bytes only. The void pointer could not allow arithmetic operation such as increment and decrement of pointer is restricted.

Example: void Pointer in C Programming
#include<stdio.h>

int main()
{
    int a = 10;
    void *ptr = &a;
    printf("%d", *(int *)ptr);
    return 0;
}

Let’s build and run this example code and observe output. The output from this program is:

Output of void Pointers
Output of void Pointers

Pointer Arithmetic

C is one of the few languages that allow pointer arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a special relationship in C language. More on this will be in next lesson i.e. arrays.

Example Program: Pointer Arithmetic
#include<stdio.h>

int main()
{
    int a = 10;
    int *p;
    p = &a;

    printf("Address of p is %d \n", p);
    printf("Value at address of p is %d \n\n", *p);

    printf("Size of integer %d bytes \n\n", sizeof(int));

    printf("Address of p+1 is %d \n", p+1);
    printf("Value at address of p+1 is %d \n", *(p+1));
}

Let’s build and run this example code and observe output. The output from this program is:

Output of Pointer Arithmetic
Output of Pointer Arithmetic

Pointer to Pointer in C Programming

Pointer to Pointer is possible and it means holding an address of pointer variable into another variable. This is why earlier in this post we said pointer is very powerful tool in C Programming Language. Pointer to pointer relations can be applied up to 12 stages but generally there is no limitation. This can also be referred as Multiple Pointers. The examples are: int *p, int **p, int ***p, don’t worry if it looks weird at first sight. Please hold on and try to understand following example code.

Example Program: Pointer to Pointer  
#include <stdio.h>

int main () {

   int  a;      // initialize variable
   int  *p;     // initialize pointer variable
   int  **ptop; // initialize pointer to pointer variable

   a = 5;       // assign 5 to "a"
   p = &a;      // hold the address of "a"
   ptop = &p;   // assign address of "p"

   /* take the value using pptr */
   printf("Value of a: %d\n", a);
   printf("Value available at *p: %d\n", *p);
   printf("Value available at **ptop: %d\n", **ptop);
}

Let’s build and run this example code and observe output. The output from this program is:

Output of Pointer to Pointer
Output of Pointer to Pointer

Pointers as Function Arguments

In C Programming, we are allowed to pass pointer to a function. In order to do so we have to declare function parameter as a pointer type. This example program will show you how it’s been used.

Example : Pointers as Function Arguments
#include <stdio.h>

void Increment(int *p);

int main()
{
    int a;
    a = 10;

    Increment(&a);
    printf("a= %d", a);
}

void Increment(int *p)
{
   *p = (*p)+1;
}

Let’s build and run this example code and observe output. The output from this program is:

Output of Pointers as Function Arguments
Output of Pointers as Function Arguments

Common Errors while using Pointer

Understanding a pointer may takes time so be patience. There are some common errors which every C learner come across. The reason to write this section is to introduce you with these common errors:

Uninitialized Pointer

There often a case especially among newbie’s. When use pointer they forget to initialize them. These pointer points to random memory location. And when we access or try to write value at that location. The program shows unpredictable behaviours. Sometimes your programs crash, run for a while and then crash, resulting garbage value or nothing will happen.

Assigning Value to Pointer Variable

int *p, a = 10;
p = a ;       // Error on This Line

p is pointer variable which is used to store the address of the variable. Pointer Variable “p” contain the address of the variable of type int as we have declared pointer variable with data type int. We are assigning value of Variable to the Pointer variable, instead of Address. In order to resolve this problem we should assign address of variable to pointer variable. Write it like this:

p = &a;

Assigning Value to Uninitialized Pointer

We are assigning the value to the pointer variable. We all know that pointer is special kind of variable which is used to store the address of another variable. So we can store only address of the variable to the pointer variable.

int *p, a=10;
*p = a;            // Error on This Line

We are going to update the value stored at address pointed by uninitialized pointer variable. Instead write it as:

int *p, a=10, b=20;
p = &b;
*p = a;

Firstly initialize pointer by assigning the address of integer to Pointer variable. After initializing pointer we can update value.

Not De-referencing Pointer Variable

De-referencing pointer is process of getting the value from the address to whom pointer is pointing to.

int *p, a=100;
p = &a;
printf("%d", p);

In this example, you will not get any compiler error but it is considered as common mistake by novice user to de-reference pointer variable without using asterisk (*) sign.

Assigning Address of Un-initialized Variable

int *p, a;
p = &a;

Best practice while using pointer is to initialize pointer before using it. We can assign any valid address to pointer variable but if you assign the address of un-initialized variable to pointer then it will print garbage value while de-referencing it.

Comparing Pointers that Points to different objects

We cannot compare two pointer variables. This is because variables may have random memory location. We cannot compare memory address.

char str1[10], str2[10];
char *p1 = str1;
char *p2 = str2;

if(p1>p2)  .....   // Error Here
{
....
....
}

NULL pointers: run-time error and segmentation fault 

The NULL pointer has a reserved value in the C Language (very often the value zero but not necessarily). It indicates that it refers to nothing. A NULL pointer should not be confused with an uninitialized pointer. Because it refers to nothing, an attempt to dereference a NULL pointer can cause a run-time error (segmentation fault).

There’s a lot of nice, tidy code you can write without knowing about pointers. But once you learn to use the pointers, you can never go back. There are too many things that can only be done with pointers. But with increased power comes increased responsibility. Pointers allow new and ugly types of bugs, and pointer bugs can crash in random ways which makes them more difficult to debug. Nonetheless, even with their problems, pointers are an irresistibly powerful programming construct. This is it, for Pointers in C Programming. In next lesson we’ll learn about Arrays in C Programming. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading.

Get Free Courses & Webinars
You'll receive only high quality learning material, tips & tricks
I agree to have my personal information transfered to MailChimp ( more information )
We respect your privacy

About Umesh Lokhande

Umesh Lokhande holds a Master degree in Scientific Instrumentation from University of Applied Sciences Jena, Germany. and has previously worked at Orbotech, Alere Technologies etc. Umesh is also a founder and first author of BINARYUPDATES.COM

Login

Register | Lost your password?