What is Pointers in C & how it works?

A pointer is a variable in the C programming language which holds the address of another variable of the same data type. For instance, an integer variable contains an integer value; however, an integer pointer holds the address of integer variable. 

Pointers in C have derived data types. Whenever a variable is initialized in the C programming language, memory is allocated to it which stores the value of the variable. With the help of ampersand (&), we can find out the address of that variable. Below mention, C  program helps you to understand "How to access the address of a variable using the ampersand (&)."


See Also: Types of pointers in C 


#include <stdio.h>
int main ( )
{
int a = 12;
printf ("Value of a=%d\n", a);
printf ("Address of a=%x\n", &a);

Output
Value of a =12
Address of a = 28ff1c (This output is different for different runs because the variable is stored at a different memory location in different runs.)



Whenever we declared a variable in the C programming language, then memory is allocated to that variable. Each memory location has its address, as we saw in the above program. Assume the variable 'i' is stored at memory location 5698 with the value '12'.

See Also: Pointer to Pointer

int i = 12;

Pointers in C














Declaration and Initialization of Pointers in C

Just like variables, pointers are also declared before using in the program. Pointer's name can be anything, but they should obey the rules of C.

See Also: Function pointer in C

Syntax to declare pointer variables
data type  *pointer_name;

For example
int *w//Integer data type (w) pointer variable
float *x; // Float (x) pointer variable
char *y; //Character data type (y) pointer variable.

With the help of asterisk (*) operator, we can access the value of the pointer. Because no value is assigned to these variables, so it contains a garbage value, and therefore they point to a memory location as shown in the figure, 

int *z

Pointers in C









Initialization of pointer variables

There are two ways to initialize pointer variables. You can get the memory location of the variable with the help of the reference operator (&), or you can directly assign one pointer variable to other pointer variables.

int   q             // Variable declaration

Pointers in C








Variable 'q' is stored at memory location 2000, which consists a garbage value.

int   *p           // Pointer variable declaration


Pointers in C









Pointer variable 'p' is stored at memory location 3000 with garbage value.

p = &q;           // Initialization of pointer variable



Pointers in C









After initialization, the pointer variable 'p' holds the address of the variable q, which is 2000.

int *p = q//Initialize pointer using another pointer

How to access a variable through the pointer variable?

Once an address of a variable is assigned to a pointer, the question arises that how to access the value of the variable using the pointer? This is done by using a unary operator (*) asterisk. This is also known as indirection operator or dereferencing operator.

#include <stdio.h>
int main ( )
{
    // Declaring variable and pointer variable
    int a, *q;

    // Initialize variable a
    a = 12;

    // Initialize pointer variable q
    q = &a;

    printf ("%d\n", *q);          //This will print the value of a
    printf ("%d\n", *&a);     // This will print the value of a
    printf ("%d\n", &a);     // This will print the address of a
    printf ("%d\n", p);       // This will print the address of a
    printf ("%d\n", &p);   // This will print the address of p


    return 0;

}

Size of Pointers in C

In the above section, we discussed what a pointer is in C?  We will discuss the size of the pointer, why the size of the pointer changes from one compiler to another compiler. 


Size of pointers in C






Above figure shows that size of integer and size of the pointers in c varies from compiler to compiler. If the compiler is 16-bit, it occupies 2 bytes, and if it's a 32-bit compiler, it occupies 4 bytes integer and pointer both are same. The reason why the pointer's size depends on the size of the compiler. 16-bit compiler contains 2^16 memory location.

Total location in the 16-bit compiler would be 2^16 = 65,536.

int a = 134;

The value of the integer 134 will be allocated in memory location between 0 to 65,536.

Size of pointers in C











int *ptr;


size of pointers in C











Because the pointer ptr is also the type of integer, the memory location will be allocated between 0 to 65,536.

ptr =&a;

Now, the pointer variable 'ptr' holds the address of the integer variable 'a.'

Size of pointers in C









Program to calculate the size of pointers in C.

#include <stdio.h>
#include <conio.h>
int main ( ) 
{
int a = 32;
char ch = 'd';
int *b;
char *cp;
b = &a;
cp = &ch;
printf ("size of pointer b is %d and cp is %d\n", sizeof(b), sizeof(cp));
return 0;
}

You all might be thinking that its output will be 1 byte for character pointer 'cp' and 4 bytes for the integer pointer 'b.' But this is not true, both the character pointer and the integer pointer will have the size of 4 bytes. Why do so, let's talk about it.

Size of pointers in C









Whenever you declare a normal variable, size varies from one data type to another type because the type of data you are storing is different.
But, when we are declaring character pointer, integer pointer and float pointer holding the address of variable 'ch,' 'a' and 'd.'

char *c = &ch;


i.e., character pointer 'c' holds the address (2034) of 'ch.'

int *= &a;

and integer pointer 'b' holds the address (5896) of the variable 'a.'

double *w = &d;

Pointer variable 'w' holds the address (9325) of the variable 'd'.

Using pointer variables always we are storing the same type of data. All pointer variables hold the address of a normal variable; it is not holding the data, so, what it is holding? It is holding the address 2034, 5896 and 9325. Pointer variable always holds the address, so, it always occupies 2 bytes memory. Pointer size is always fixed because it is holding address instead of data.

Arithmetic Operation on Pointers

At the time of the program, we need to perform an arithmetic operation on the pointer. But before using the arithmetic operation on the pointer, it is essential to understand the limitation of arithmetic operators with the pointers. The C programming language has a lot of arithmetic operators, but, we can only use increment or decrement operators with pointers.

The arithmetic operation can be performed on pointers. A pointer can be:
Incremented
Decremented
An integer value can be added to the pointer
An integer value can be subtracted from the pointer

When you are working with pointers, you should take care of the priority rule.
1) The operator '*' and '&' have the same priority.
2) In the same statement, the operators '*', '&', '++', '--' are evaluate from right to left.

Increment/Decrement Operation on Pointer

When we increment or decrement the pointer, the pointer points to the next/previous memory location. Below mention C program helps you understand the working of increment operation on pointers in C.

#include <stdio.h>
int main()
{
int arr[3]={10,20,30}; //Initialize Array 'arr' with three elements
int *ptr; //Declared Pointer 'ptr'
int i; //Declare integer variable 'i'
ptr=&arr; //Assigning initial address of array 'arr' to pointer 'ptr'
for (i=0;i<3;i++)
{
printf ("Value of pointer *ptr =%d\n", *ptr);
printf ("Value of ptr =%p\n", ptr);
ptr++;
}
return 0;
}


Output
Value of pointer *ptr = 10
Value of ptr = 0028FF0C
Value of *ptr=20
Value of ptr =0028FF10
Value of *ptr=30
Value of ptr = 0028FF14


C program helps you to understand decrement operation on pointers in C
#include <stdio.h>
int main()
{
int arr[3]={10,20,30};
int *ptr;
int i;
ptr=&arr;
for (i=0;i<3;i++)
{
printf ("Value of pointer *ptr =%d\n", *ptr);
printf ("Value of ptr =%p\n", ptr);
ptr++;
}
printf ("\n\n");
for (i=0;i<=3;i++)
{
printf ("Value of pointer *ptr =%d\n",*ptr);
printf ("Value of ptr =%p\n",ptr);
ptr--;
}
return 0;
}


Output
Value of pointer *ptr = 10
Value of ptr = 0028FF0C
Value of *ptr=20
Value of ptr =0028FF10
Value of *ptr=30
Value of ptr = 0028FF14
Value of pointer *ptr= 30
Value of ptr = 0028FF14
Value of *ptr=20
Value of ptr =0028FF10
Value of pointer *ptr = 10
Value of ptr = 0028FF0C

Comparison of Pointers in C

You can compare two pointers using relational operator. Six types of comparison operation you can performed '<', '>', '<=', '>=", '==', '!=' .


C program demonstrates the comparison of pointers.
#include <stdio.h>
int main()
{
int arr[3]={10,20,30}; //Initialize array
int *ptr, *ptr1; // Declare pointer 'ptr' and 'ptr1'
ptr=&arr[0]; //Assign address of 0th element i.e. arr[0] to pointer 'ptr'
ptr1=&arr[2]; //Assign address of 2nd element i.e. arr[2] to pointer 'ptr1'
if (ptr == ptr1)
{
printf ("Both pointers points to the same memory location");
}
printf ("Both pointers point to different memory location\n");
return 0;
}

Output
Both pointers point to different memory location.

Pointers and Arrays

Elements of the array can be accessed using the index, but pointers replaced it. Pointers make access of each element easier. In the C programming language, pointer and array are close to each other. Name of the array is the first element of the pointer.

Program demonstrates the Array name as pointers in C.#include <stdio.h>int main()
{

int arr[3]={10,20,30};
int *ptr,i;
ptr = arr; //Assign address of array to pointer ptr
//Or you can assign address of arr to pointer ptr, ptr=&arr[0];
for (i=0;i<3;i++)
{
printf ("Value of ptr %d\n", *ptr);
ptr++;
}
return 0;
}

Output
Value of ptr 10
Value of ptr 20
Value of ptr 30

Pointers and Strings

Strings are array of characters, ended with null character ‘\0’. Let see, how to access elements of strings using pointers.

#include <stdio.h>
#include <string.h>
int main()
{

char str[]="HELLO"; //Declare a string
int l,i;
char *ptr; //Declare pointer
l=strlen(str); //Calculate length of string
printf ("%d\n",l);
ptr = &str[0]; //Assign initial address to pointer
for (i=0;i<l;i++)
{printf ("Value of pointer %c\n", *ptr);
ptr++;
}
return 0;
}

Output
Value of pointer H
Value of pointer E
Value of pointer L
Value of pointer L
Value of pointer O

Common Mistakes in Pointers in C

Some of the mistakes that most programmers do.

Omitting Pointer

int *ptr1,ptr2;
In the above statement, integer pointer *ptr1 and integer ptr2 is declared. But the intention is to declare Pointer ‘*ptr1’ and pointer ‘*ptr2’. So, the correct statement is,
int *ptr1, *ptr2;
It is the smallest mistake done by the programmers.

Uninitialized Pointer

When a programmer is not assigning a valid address to the pointer before using it. Or a programmer tries to assign a value to the uninitialized pointer then we will get the runtime error.
#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

When programmer try to compare two different pointer which is pointing to different memory. We can compare the pointer if they pointing to the same array.
#include <stdio.h>
#include <string.h>

int main()
{char str[7]="WORLD";
char str1[7]="HELLO";
char *ptr1, *ptr2;
ptr1=str; //Assigning the initial address of array a[] to the pointer 'ptr1'
ptr2=str1; //Assigning the initial address of array b[] to the pointer 'ptr2'
if (ptr1>ptr2) //Compare Pointer ptr1 and ptr2 (iilegal statement)
{//statement
}return 0;
}

Ilegal Indirection

Whenever we declare a pointer or use a pointer, we need to be aware which value is used by pointers in c. Assume, malloc function is used to allocate memory. This malloc function allocates memory block to the pointer.
*int ptr = malloc(sizeof(int)); //Invalid statement
The above statement is incorrect. The correct method to allocate memory is,
int ptr=malloc(sizeof(int)); //Valid statement

Pointer Pointing Invalid Address

A run-time error is created if pointer pointing to the invalid memory address.
#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;
}






































What is Pointers in C & how it works? What is Pointers in C & how it works? Reviewed by Glory on 13:09 Rating: 5
Powered by Blogger.