Learning coding means GreatToCode Be more than a Coder ! Greattocode , Join GreatToCode Community,1000+ Students Trusted On Us .If You want to learn coding, Then GreatToCode Help You.No matter what It Takes !


CODE YOUR WAY TO A MORE FULFILLING And HIGHER PAYING CAREER IN TECH, START CODING FOR FREE Camp With GreatToCode - Join the Thousands learning to code with GreatToCode
Interactive online coding classes for at-home learning with GreatToCode . Try ₹Free Per Month Coding Classes With The Top Teachers . What is Pointer in C?

What is Pointer in C?

 



What is Pointer in C?

•The pointer in C language is a variable which stores the

address of another variable.


•This variable can be of type int, char, array, function, or

any other pointer.


• The purpose of pointer is to save memory space and achieve faster

execution time.


Declaration of C Pointer

variable


The general syntax of pointer declaration is


data_type *var_name;


Initialization of C Pointer variable


int a = 10;

int *ptr; //pointer declaration

ptr = &a; //pointer initialization


Address


Value


Variable Name


10


a

5001


*ptr

5002


5001


#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: %u\n", &var );


/* address stored in pointer variable */

printf("Address stored in ip variable: %u\n", ip );

printf("Address of ip variable: %u\n",&ip );

//display address of ip variable


/* access the value using the pointer */

printf("Value of *ip variable: %d\n", *ip );


}


Address of var variable: 1449960548

Address stored in ip variable: 1449960548

Value of *ip variable: 20


int *pc, c;

c = 5;

pc = &c;

c = 1;

printf("%d", c); // Output: 1

printf("%d", *pc); // Output: 1


int *pc, c, d;

c = 5;

d = -15;

pc = &c;

printf("%d", *pc);

// Output: 5

pc = &d;

printf("%d", *pc);

// Output: -15

printf(“%d”, *(&d));

//Output: -15


Pointer Arithmetic


We can perform arithmetic operations on the pointers like

addition, subtraction, etc. However, as we know that pointer

contains the address, the result of an arithmetic operation

performed on the pointer will also be a pointer if the other

operand is of type integer.

In pointer-from-pointer subtraction, the result will be an integer

value. Following arithmetic operations are possible on the pointer

in C language:

• Increment

• Decrement

• Addition

• Subtraction

• Comparison


Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start

pointing to the immediate next location. This is

somewhat different from the general arithmetic since the

value of the pointer will get increased by the size of the

data type to which the pointer is pointing.


We can traverse an array by using the increment

operation on a pointer which will keep pointing to every

element of the array, perform some operation on that,

and update itself in a loop.

The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type)


•Where i is the number by which the pointer get increased.


• 32-bit

For 32-bit int variable, it will be incremented by 2 bytes.


• 64-bit

For 64-bit int variable, it will be incremented by 4 bytes.


•Let's see the example of incrementing pointer variable on 64-bit

architecture.


Let's see the example of Incrementing pointer variable on 64-bit architecture.

#include<stdio.h>

int main()

{

int number=50;

int *p; //pointer to int

p=&number; //stores the address of number variable

printf("Address of p variable is %u \n",p);

p=p+1;

printf("After increment: Address of p variable is %u \n",p);

// in our case, p will get incremented by 4 bytes.

return 0;

}


Output

Address of p variable

is

3214864300


After increment:

Address of p variable

is

3214864304


Decrementing pointer variable on 64-bit OS.


#include <stdio.h>

void main(){

int number=50;

int *p; //pointer to int

p=&number;//stores the address of number variable

printf("Address of p variable is %u \n",p);

p=p-1;

printf("After decrement: Address of p variable is %u \n",p); //

P will now point to the immediate previous location.

}


Output


Address of p variable is

3214864300


After decrement: Address of

p variable is 3214864296


#include <stdio.h>

const int MAX = 3;

int main ()

{


int var[] = {10, 100, 200};

int i, *ptr;

ptr = var; /* let us have array address in pointer */

for ( i = 0; i < MAX; i++)

{

printf("Address of var[%d] = %u\n", i, ptr );

printf("Value of var[%d] = %d\n", i, *ptr );

ptr++; /* move to the next location */

}


}


Output


Address of var[0] =1030875764

Value of var[0] = 10


Address of var[1] = 1030875768

Value of var[1] = 100


Address of var[2] = 1030875774

Value of var[2] = 200


#include <stdio.h>

const int MAX = 3;

int main ()

{

int var[] = {10, 100, 200};

int i, *ptr;

ptr = &var[MAX-1]; // let us have array address in pointer

for ( i = MAX; i > 0; i--)

{

printf("Address of var[%d] = %u\n", i-1, ptr );

printf("Value of var[%d] = %d\n", i-1, *ptr );

/* move to the previous location */

ptr--;

}


}


Output


Address of var[2] =2632962588

Value of var[2] = 200


Address of var[1] =2632962584

Value of var[1] = 100


Address of var[0] =2632962580

Value of var[0] = 10


#include<stdio.h>

void main()

{

int a[3] = {1, 2, 3};

int *p = a;

for (int i = 0; i < 3; i++)

{

printf("%d\t", *p);

p++;

}

}

Output:

1 2 3


Illegal arithmetic with pointers

1. Address + Address = illegal

2. Address * Address = illegal

3. Address % Address = illegal

4. Address / Address = illegal

5. Address & Address = illegal

6. Address ^ Address = illegal

7. Address | Address = illegal

8. ~Address = illegal


Pointer to a Pointer in C (Double Pointer)

Pointer are used to store the address of other variables of

similar datatype.

But if you want to store the address of a pointer variable, then

you again need a pointer to store it.

Thus, when one pointer variable stores the address of another

pointer variable, it is known as Pointer to Pointer variable

or Double Pointer.


Syntax:

int **p1;


Pointer to a Pointer in C (Double Pointer)

A pointer to a pointer is a form of multiple indirection, or a chain of pointers.

Normally, a pointer contains the address of a variable. When we define a pointer to

a pointer, the first pointer contains the address of the second pointer, which points to

the location that contains the actual value as shown below.


A variable that is a pointer to a pointer must be declared as such. This is done by

placing an additional asterisk in front of its name. For example, the following

declaration declares a pointer to a pointer of type int −

Syntax:

int **var;


#include <stdio.h>

int main ()

{

int var, *ptr, **pptr;

var = 3000;

ptr = &var; /* take the address of var */


pptr = &ptr;

/* take the value using pptr */

printf("Value of var = %d\n", var );

printf("Value available at *ptr = %d\n", *ptr );

printf("Value available at **pptr = %d\n", **pptr);

}


Output


Value of var = 3000


Value available at *ptr = 3000


Value available at **pptr = 3000


Pointer and Arrays in C


The continuous memory locations are allocated of every array be

compiled in computer memory. The location of the first element of the

array is called a base address.


For example: int a[4]={10,20,30,40};


p1=x; or p1=&x[0];


u


#include <stdio.h>

int main()

{

int a[5]={1,2,3,4,5}; //array initialization

int *p; //pointer declaration

/*the ptr points to the first element of the array*/


p=a;

printf("Printing the array elements using pointer\n");

for(int i=0;i<5;i++) //loop for traversing array elements

{

printf("\t%d",*p); //printing array elements

p++; //incrementing to the next element, you can also write p=p+1

}

return 0;

}

Output: 1 2 3 4 5


#include <stdio.h>

int main() {

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

int* ptr;


// ptr is assigned the address of the third element

ptr = &x[2];


printf("*ptr = %d \n", *ptr);

printf("*(ptr+1) = %d \n", *(ptr+1));

printf("*(ptr-1) = %d", *(ptr-1));


return 0;

}


Output

//3

//4

//2


Pointer to Multidimensional Array


Pointer to Function


•In C programming, it is also possible to pass addresses

as arguments to functions.

•To accept these addresses in the function definition, we

can use pointers. It's because pointers are used to store

addresses.


#include <stdio.h>

void swap(int *n1, int *n2);

int main() {

int num1 = 5, num2 = 10;

// address of num1 and num2 is passed

swap( &num1, &num2);

printf("num1 = %d\n", num1);

printf("num2 = %d", num2);

return 0; }

void swap(int* n1, int* n2) {

int temp;

temp = *n1;

*n1 = *n2;

*n2 = temp; }


Output


num1 = 10

num2 = 5


Functions returning Pointer variables


•A function can also return a pointer to the calling function.

•In this case you must be careful, because local variables of function

doesn't live outside the function.

•They have scope only inside the function.

•Hence if you return a pointer connected to a local variable, that pointer

will be pointing to nothing when the function ends.


#include <stdio.h>

int* larger(int*, int*);

void main() {

int a = 15;

int b = 92;

int *p;

p = larger(&a, &b);

printf("%d is larger",*p); }

int* larger(int *x, int *y) {

if(*x > *y)

return x;

else

return y; }


Output

92 is larger


Pointer to functions


It is possible to declare a pointer pointing to a function which can then

be used as an argument in another function. A pointer to a function is

declared as follows,


Syntax:

type (*pointer-name)(parameter);


Example :

int (*sum)(); //legal declaration of pointer to function

int *sum(); //This is not a legal declaration of pointer to function


#include <stdio.h>

int sum(int x, int y) {

return x+y; }


int main( ) {

int (*fp)(int, int);

fp = sum;

int s = fp(10, 15);

printf("Sum is %d", s);

return 0; }


Output


25


Static Memory Allocation


As you know, an array is a collection of a fixed number of values.

Once the size of an array is declared, you cannot change it.


Sometimes the size of the array you declared may be insufficient.

To solve this issue, you can allocate memory manually during

run-time. This is known as dynamic memory allocation in C

programming.


Dynamic Memory Allocation in C


•Dynamic Memory Allocation is manual allocation and freeing of

memory according to your programming needs.

•Dynamic memory is managed and served with pointers that

point to the newly allocated memory space in an area which we

call the heap.

•Now you can create and destroy an array of elements

dynamically at runtime without any problem.


To allocate memory dynamically, library

functions are used


1. malloc()

2. calloc()

3. realloc()

4. free()

These functions are defined in the <stdlib.h> header file.


malloc()

• The name "malloc" stands for memory allocation.

• The malloc() function reserves a block of memory of the specified number

of bytes. And, it returns a pointer of void which can be casted into pointers

of any form.

• It initializes each block with default garbage value

Syntax of malloc()

ptr = (data-type*) malloc(byte-size)

For Example:

ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr

holds the address of the first byte in the allocated memory.


Output:

Enter number of elements: 5

Memory successfully allocated

using malloc.

The elements of the array are:

1, 2, 3, 4, 5,


#include <stdio.h>

#include <stdlib.h>

int main()

{

int *ptr, n = 5,i;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()

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

// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

}

else {

printf("Memory successfully allocated using malloc.\n");

for (i = 0; i < n; ++i)


{


ptr[i] = i + 1;

}

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

}

}

}


calloc()

The name "calloc" stands for contiguous allocation.


The malloc() function allocates memory and leaves the memory uninitialized,

whereas the calloc() function allocates memory and initializes all bits to zero.


Syntax of calloc()

ptr = (DataType*)calloc(n, size);

Example:

ptr = (float*) calloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25 elements of type

float.


Output:

Enter number of

elements: 5

Memory successfully

allocated using calloc.

The elements of the array

are: 1, 2, 3, 4, 5


#include <stdio.h>

#include <stdlib.h>

int main()

{

int *ptr, n=5, i;

printf("Enter number of elements: %d\n", n);

ptr = (int*)calloc(n, sizeof(int));

if (ptr == NULL) /* Check memory successfully allocated by calloc or not */

{

printf("Memory not allocated.\n");

exit(0);

}

else {

printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array

for (i = 0; i < n; ++i) {

ptr[i] = i + 1;

}

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

}

}

}


realloc()

“realloc” or “re-allocation” method in C is used to dynamically change the

memory allocation of a previously allocated memory.

In other words, if the memory previously allocated with the help of malloc or

calloc is insufficient,

realloc can be used to dynamically re-allocate memory.

re-allocation of memory maintains the already present value and new blocks

will be initialized with default garbage value.


Syntax:

ptr = realloc(ptr, newSize);


where ptr is reallocated with new size 'newSize'.


Output:

Enter number of elements: 5

Memory successfully allocated

using calloc.

The elements of the array are: 1,

2, 3, 4, 5,


Enter the new size of the array:

10

Memory successfully re-allocated

using realloc.

The elements of the array are: 1,

2, 3, 4, 5, 6, 7, 8, 9, 10,


#include <stdio.h>

#include <stdlib.h> int main() {

int *ptr, n=5, i;

printf

("Enter number of elements: %d\n", n);

ptr = (int*)calloc(n, sizeof

(int));


if (ptr == NULL) {

printf


("Memory not allocated.\n");


exit(0);

}

else

{

printf


("Memory successfully allocated using calloc.\n");


for (i = 0; i < n; ++i) {

ptr[i] = i + 1;

}

printf


("The elements of the array are: ");


for (i = 0; i < n; ++i) {

printf


("%d, ", ptr[i]);

}

printf


("\n\nEnter the new size of the array: %d\n", n);


ptr = realloc(ptr, n * sizeof

(int));


printf


("Memory successfully re-allocated using realloc.\n");


for (i = 5; i < n; ++i) {

ptr[i] = i + 1;

}

printf


("The elements of the array are: ");


for (i = 0; i < n; ++i) {

printf


("%d, ", ptr[i]);

}

free(ptr);

}

}


free()


“free” method in C is used to dynamically de-allocate the

memory.

The memory allocated using functions malloc() and calloc() is not

de-allocated on their own.

Hence the free() method is used, whenever the dynamic memory

allocation takes place.

It helps to reduce wastage of memory by freeing it.


Syntax:

free(ptr);


Function Purpose

malloc() Allocates the memory of requested size and

returns the pointer to the first byte of allocated

space.


calloc() Allocates the space for elements of an array.

Initializes the elements to zero and returns a

pointer to the memory.


realloc() It is used to modify the size of previously


allocated memory space.


Free() Frees or empties the previously allocated


memory space.


Uses of pointers:


1.To pass arguments by reference

2.For accessing array elements

3.To return multiple values

4. Dynamic memory allocation

5.To implement data structures


Features of Pointers:


1.Pointers save memory space.

2.Execution time with pointers is faster because data are

manipulated with the address, that is, direct access to

memory location.

3.Memory is accessed efficiently with the pointers. The pointer

assigns and releases the memory as well. Hence it can be

said the Memory of pointers is dynamically allocated.

4.Pointers are used with data structures. They are useful for

representing two-dimensional multi-dimensionalarrays.

5.An array, of any type can be accessed with the help of

pointers, without considering its subscript range.

6.Pointers are used for file handling.


Benefits of using pointers


1.Pointers are more efficient in handling Arrays and Structures.

2.Pointers allow references to function and thereby helps in

passing of function as arguments to other functions.

3. It reduces length of the program and its execution time as well.

4. It allows C language to support Dynamic Memory management.


References for Pointers Theory & Program


• https://www.tutorialspoint.com/cprogramming/c_pointers.htm

• https://www.programiz.com/c-programming/c-pointers

• https://www.javatpoint.com/c-pointers

• https://beginnersbook.com/2014/01/c-pointers/

• https://www.studytonight.com/c/pointers-in-c.php


• https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-

malloc-calloc-free-and-realloc/


• https://www.programiz.com/c-programming/c-dynamic-memory-allocati

on

• https://www.geeksforgeeks.org/c-dynamic-memory-allocation-question-4

/?ref=rp


References for MCQ on Pointer


• https://www.geeksforgeeks.org/c-language-2-gq/pointers-gq/

• https://www.sanfoundry.com/multiple-choice-questions-c-pointers-function-arguments/

• https://www.examveda.com/c-program/practice-mcq-question-on-pointer/

• https://www.indiabix.com/c-programming/pointers/

• http://www.allindiaexams.in/engineering/cse/c-multiple-choice-questions-answers/pointers

• https://letsfindcourse.com/technical-questions/c/functions-pointers


• https://tutorialslink.com/mcq-quiz/pointers-in-c-programming-mcq-multiple-choice-questions-

and-answers

Post a Comment

0 Comments

•Give The opportunity to your child with GreatToCode Kid's • Online Coding Classes for Your Kid • Introduce Your kid To the world's of coding
•Fuel You Career with our 100+ Hiring Partners, Advance Your Career in Tech with GreatToCode. •Join The Largest Tech and coding Community and Fast Forward Your career with GreatToCode. •10000+ Learner's+ 90 % placement Guarantee. • Learning Coding is Better with the GreatToCode community .
•Greattocode Kid's •GreatToCode Career •GreatToCode Interview •GreatToCode Professional •GreatToCode for schools •GreatToCode For colleges •GreatToCods For Businesses.
Are you ready to join the millions of people learning to code? GreatToCode Pass is your one-stop-shop to get access to 1000+ courses, top-notch support, and successful job placement. What are you waiting for? Sign up now and get your future in motion with GreatToCode Pass.