Skip to content
Related Articles
Open in App
Not now

Related Articles

C Pointers

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 27 Dec, 2022
Improve Article
Save Article

 Pointers in C are used to store the address of variables or a memory location. This variable can be of any data type i.e, int, char, function, array, or any other pointer. The pointer of type void is called Void pointer or Generic pointer. Void pointer can hold address of any type of variable. The size of the pointer depends on the computer architecture like 16-bit, 32-bit, and 64-bit.

Syntax:

datatype *var_name; 

Let pointer “ptr” holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through “ptr”. So to define “ptr” we can do it in four ways, which are as following:

int *ptr; 
int* ptr;
int * ptr;
int*ptr;
C pointers

 

Example:

C




// C program to illustrate Pointers
#include <stdio.h>
 
void geeks()
{
    int var = 20;
 
    // declare pointer variable
    int* ptr;
 
    // note that data type of ptr and var must be same
    ptr = &var;
 
    // assign the address of a variable to a pointer
    printf("Value at ptr = %p \n", ptr);
    printf("Value at var = %d \n", var);
    printf("Value at *ptr = %d \n", *ptr);
}
 
// Driver program
int main()
{
    geeks();
    return 0;
}


Output

Value at ptr = 0x7ffd15b5deec 
Value at var = 20 
Value at *ptr = 20 

Uses of pointer

  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
  6. To do System-Level Programming where memory addresses are useful
  7. To help locating exact value at exact location.
  8. To avoid compiler confusion for same variable name.
  9. To use in Control Tables.

How to Use Pointers?

To use pointers in C, we must understand below two operators. 

1. To access the address of a variable to a pointer, we use the unary or Address of operator & (ampersand) that returns the address of that variable. For example &x gives us the address of variable x. 

C




// The output of this program can be different
// in different runs. Note that the program
// prints address of a variable and a variable
// can be assigned different address in different
// runs.
#include <stdio.h>
 
int main()
{
    int x;
 
    // Prints address of x
    printf("%p", &x);
 
    return 0;
}


Output

0x7fffd60dddfc

2. One more operator is unary or dereference operator * (Asterisk) which is used for two things: 

2.A. To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name. 
 

C




// C program to demonstrate declaration of
// pointer variables.
#include <stdio.h>
int main()
{
    int x = 10;
 
    // 1) Since there is * in declaration, ptr
    // becomes a pointer variable (a variable
    // that stores address of another variable)
    // 2) Since there is int before *, ptr is
    // pointer to an integer type variable
    int* ptr;
 
    // & operator before x is used to get address
    // of x. The address of x is assigned to ptr.
    ptr = &x;
 
    return 0;
}


2.B. To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand. This is also called Dereferencing.

C




// C program to demonstrate use of * for pointers
#include <stdio.h>
 
int main()
{
    // A normal integer variable
    int Var = 10;
 
    // A pointer variable that holds address of var.
    int* ptr = &Var;
 
    // This line prints value at address stored in ptr.
    // Value stored is value of variable "var"
    printf("Value of Var = %d\n", *ptr);
 
    // The output of this line may be different in different
    // runs even on same machine.
    printf("Address of Var = %p\n", ptr);
 
    // We can also use ptr as lvalue (Left hand
    // side of assignment)
    *ptr = 20; // Value at address is now 20
 
    // This prints 20
    printf("After doing *ptr = 20, *ptr is %d\n", *ptr);
 
    return 0;
}


Output

Value of Var = 10
Address of Var = 0x7ffd11cd52ac
After doing *ptr = 20, *ptr is 20
Pictorial Representation of Pointer in C

 

Pointer Expressions and Pointer Arithmetic

 A limited set of arithmetic operations can be performed on pointers. The Pointer Arithmetic is slightly different from the ones that we generally use for mathematical calculations. The operations are: 

  • Increment/Decrement of a Pointer
  • Addition of integer to a pointer
  • Subtraction of integer to a pointer
  • Subtracting two pointers of the same type
  • Comparison of pointers of the same type.
  • Assignment of pointers to the same type of pointers.

Pointer arithmetic is meaningless unless performed on an array. 

Note: Pointers contain addresses. Adding two addresses makes no sense, because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between these two addresses.

C




// C program to illustrate Pointer Arithmetic
 
#include <stdio.h>
 
int main()
{
 
    // Declare an array
    int v[3] = { 10, 100, 200 };
 
    // Declare pointer variable
    int* ptr;
 
    // Assign the address of v[0] to ptr
    ptr = v;
 
    for (int i = 0; i < 3; i++) {
       
          // print value at address which is stored in ptr
        printf("Value of *ptr = %d\n", *ptr);
       
          // print value of ptr
        printf("Value of ptr = %p\n\n", ptr);
 
        // Increment pointer ptr by 1
        ptr++;
    }
    return 0;
}


Output

Value of *ptr = 10
Value of ptr = 0x7ffe8ba7ec50

Value of *ptr = 100
Value of ptr = 0x7ffe8ba7ec54

Value of *ptr = 200
Value of ptr = 0x7ffe8ba7ec58
Pictorial Representation of Pointer in C

 

Array Name as Pointers 

An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably. 

C




#include <stdio.h>
 
void geeks()
{
    // Declare an array
    int val[3] = { 5, 10, 15 };
 
    // Declare pointer variable
    int* ptr;
 
    // Assign address of val[0] to ptr.
    // We can use ptr=&val[0];(both are same)
    ptr = val;
   
    printf("Elements of the array are: ");
   
      printf("%d, %d, %d",ptr[0],ptr[1],ptr[2]);
 
    return;
}
 
// Driver program
int main()
{
    geeks();
    return 0;
}


Output

Elements of the array are: 5 10 15
Pointer in C

 

Now if this ptr is sent to a function as an argument then the array val can be accessed in a similar fashion. 

Pointers and Multidimensional Arrays 

Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration 

int nums[2][3]  =  { {16, 18, 20}, {25, 26, 27} };

In general, nums[i][j] is equivalent to *(*(nums+i)+j)

Pointer Notation Array Notation Value
*(*nums) nums[0][0] 16
*(*nums + 1) nums[0][1] 18
*(*nums + 2) nums[0][2] 20
*(*(nums + 1)) nums[1][0] 25
*(*(nums + 1) + 1) nums[1][1] 26
*(*(nums + 1) + 2) nums[1][2] 27

Advantages of Pointers

  • Pointers are used for dynamic memory allocation and deallocation.
  • An Array or an structure can be accessed efficiently with pointers
  • Pointers are useful for accessing memory locations.
  • Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
  • Pointers reduces length of the program and its execution time as well.

Disadvantages of pointers

  • Memory corruption can occur if an incorrect value is provided to pointers
  • Pointers are Complex to understand.
  • Pointers are majorly responsible for memory leaks.
  • Pointers are comparatively slower than variables in C.
  • Uninitialized pointers might cause segmentation fault.

Void Pointers

A Void Pointer in C can be defined as an address of any variable. It has no standard data type. A void pointer is created by using the keyword void.

C




// C Program to show void pointer
#include <stdio.h>
 
int main()
{
    // void pointer
    void* ptr = NULL;
 
    printf("The size of pointer is:%d\n", sizeof(ptr));
 
    return 0;
}


Output

The size of pointer is:8

NULL Pointers

Null pointers can be created by assigning a zero value during pointer declaration. This method is useful when no address is assigned to the pointer.

Syntax:

int * ptr = NULL;

Example:

C




// C program to show use of Null Pointer
#include <stdio.h>
 
int main()
{
    // null pointer
    int* ptr = NULL;
 
    printf("The value inside variable ptr is:\n%x", ptr);
 
    return 0;
}


Output

The value inside variable ptr is:
0

Wild Pointers 

Wild Pointers are pointers that have not been initialized with something yet. These types of C-pointers can cause problems in our programs and can eventually cause them to crash. While working with Wild Pointers Programmer must be very careful.

C




// C Program to show use of wild pointers
#include <stdio.h>
 
int main()
{
    // wild pointer
    int* ptr;
 
    printf("\n%d", *ptr);
   
    return 0;
}


Output:

timeout: the monitored command dumped core

/bin/bash: line 1:    32 Segmentation fault      timeout 15s ./543664c1-f84d-4498-ba9b-4f209538f96a < 543664c1-f84d-4498-ba9b-4f209538f96a.in

Other types of pointers in C are as follows:

  • Far pointer – A far pointer is typically 32 bit that can access memory outside current segment.
  • Dangling pointer – A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.
  • Huge pointer – A huge pointer is 32 bit long containing segment address and offset address.
  • Complex pointer – Pointers with multiple levels of indirection.
  • Near pointer – Near pointer is used to store 16 bit addresses means within current segment on a 16 bit machine.
  • Normalized pointer – It is a 32 bit pointer, which has as much of its value in the segment register as possible.
  • Generic pointer – In C void* acts as a generic pointer.
  • File Pointer – The pointer to a FILE data type is called as a stream pointer or a file pointer.

Questions:

Q1: Are pointers integer?

Ans: No, pointers are not integers. A pointer is an address. It is a positive number.

Q2: What does the error ‘Null Pointer Assignment’ means and what causes this error?

Ans: As null pointer points to nothing so accessing a uninitialized pointer or invalid location may cause an error.

Q3: How pointer variables are initialized?

Ans: Pointer variables are initialized by one of the following ways.

  • Static memory allocation
  • Dynamic memory allocation

Q4: What is pointer to a pointer?

Ans: If a pointer variable points another pointer value. Such a situation is known as a pointer to a
pointer.
Example:
int *p1,**p2,v=10;
P1=&v; p2=&p1;
Here p2 is a pointer to a pointer.

Q5: What is an array of pointers?

Ans: if the elements of an array are addresses, such an array is called an array of pointers.

Q6: Difference between array and pointer?

Ans:
Array:

  • Array allocates space automatically.
  • It cannot be resized.
  • It cannot be reassigned.
  • sizeof (arrayname) gives the number of bytes occupied by the array.

Pointer:

  • Explicitly assigned to point to an allocated space.
  • It can be sized using realloc().
  • Pointer can be reassigned.
  • sizeof (p) returns the number of bytes used to store the pointer variable p.

Q7: What are the pointer declarations used in C?

Ans.
Array of pointers, e.g , int *a[10]; Array of pointers to integer
Pointers to an array,e.g , int (*a)[10]; Pointer to an array of into
Function returning a pointer,e.g, float *f( ) ; Function returning a pointer to float
Pointer to a pointer ,e.g, int **x; Pointer to a pointer to int
Pointer to a data type ,e.g, char *p; pointer to char

Q8: Differentiate between a constant pointer and pointer to a constant?

Ans:
const char *p; //pointer to a const character.
char const *p; //pointer to a const character.
char * const p; //const pointer to a char variable.
const char * const p; // const pointer to a const character

Must Read: Applications of pointers in C/C++.Quizzes:

This article is contributed by Abhirav Kariya. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!