The Wayback Machine - https://web.archive.org/web/20241109062916/https://www.geeksforgeeks.org/c-pointers/
Open In App

C Pointers

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C.

In this article, we will discuss C pointers in detail, their types, uses, advantages, and disadvantages with examples.

What is a Pointer in C?

A pointer is defined as a derived data type that can store the address of other C variables or a memory location. We can access and manipulate the data stored in that memory location using pointers.

As the pointers in C store the memory addresses, their size is independent of the type of data they are pointing to. This size of pointers in C only depends on the system architecture. If you’re looking to master pointers, especially how they work with data structures, the C Programming Course Online with Data Structures offers a comprehensive breakdown of this concept.

Syntax of C Pointers

The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration.

datatype * ptr;

where

  • ptr is the name of the pointer.
  • datatype is the type of data it is pointing to.

The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures, etc.

How to Use Pointers?

The use of pointers in C can be divided into three steps:

  1. Pointer Declaration
  2. Pointer Initialization
  3. Pointer Dereferencing

1. Pointer Declaration

In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name.

Example

int *ptr;

The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.

2. Pointer Initialization

Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( &: ampersand ) addressof operator to get the memory address of a variable and then store it in the pointer variable.

Example

int var = 10;
int * ptr;
ptr = &var;

We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time.

Example

int *ptr = &var;

Note: It is recommended that the pointers should always be initialized to some value before starting using it. Otherwise, it may lead to number of errors.

3. Pointer Dereferencing

Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration.

dereferencing a pointer in c

Dereferencing a Pointer in C

C Pointer Example

C
// C program to illustrate Pointers
#include <stdio.h>

void geeks()
{
    int var = 10;

    // 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 = 0x7ffca84068dc 
Value at var = 10 
Value at *ptr = 10 

Types of Pointers in C

Pointers in C can be classified into many different types based on the parameter on which we are defining their types. If we consider the type of variable stored in the memory location pointed by the pointer, then the pointers can be classified into the following types:

1. Integer Pointers

As the name suggests, these are the pointers that point to the integer values.

Syntax

int *ptr;

These pointers are pronounced as Pointer to Integer.

Similarly, a pointer can point to any primitive data type. It can point also point to derived data types such as arrays and user-defined data types such as structures.

2. Array Pointer

Pointers and Array are closely related to each other. Even the array name is the pointer to its first element. They are also known as Pointer to Arrays. We can create a pointer to an array using the given syntax.

Syntax

char *ptr = &array_name;

Pointer to Arrays exhibits some interesting properties which we discussed later in this article.

3. Structure Pointer

The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can be declared in the same way as we declare the other primitive data types.

Syntax

struct struct_name *ptr;

In C, structure pointers are used in data structures such as linked lists, trees, etc.

4. Function Pointers

Function pointers point to the functions. They are different from the rest of the pointers in the sense that instead of pointing to the data, they point to the code. Let’s consider a function prototype – int func (int, char), the function pointer for this function will be

Syntax

int (*ptr)(int, char);

Note: The syntax of the function pointers changes according to the function prototype.

5. Double Pointers

In C language, we can define a pointer that stores the memory address of another pointer. Such pointers are called double-pointers or pointers-to-pointer. Instead of pointing to a data value, they point to another pointer.

Syntax

datatype ** pointer_name;

Dereferencing Double Pointer

*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer

Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3, ****ptr4, ******ptr5 and so on.

6. NULL Pointer

The Null Pointers are those pointers that do not point to any memory location. They can be created by assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.

Syntax

data_type *pointer_name = NULL;
or
pointer_name = NULL

It is said to be good practice to assign NULL to the pointers currently not in use.

7. Void Pointer

The Void pointers in C are the pointers of type void. It means that they do not have any associated data type. They are also called generic pointers as they can point to any type and can be typecasted to any type.

Syntax

void * pointer_name;

One of the main properties of void pointers is that they cannot be dereferenced.

8. Wild Pointers

The 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. If values is updated using wild pointers, they could cause data abort or data corruption.

Example

int *ptr;
char *str;

9. Constant Pointers

In constant pointers, the memory address stored inside the pointer is constant and cannot be modified once it is defined. It will always point to the same memory address.

Syntax

data_type * const pointer_name;

10. Pointer to Constant

The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here we can only access the data pointed by the pointer, but cannot modify it. Although, we can change the address stored in the pointer to constant.

Syntax

const data_type * pointer_name;

Other Types of Pointers in C:

There are also the following types of pointers available to use in C apart from those specified above:

  • Far pointer: A far pointer is typically 32-bit that can access memory outside the current segment.
  • Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a 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 the 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.
  • File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

Size of Pointers in C

The size of the pointers in C is equal for every pointer type. The size of the pointer does not depend on the type it is pointing to. It only depends on the operating system and CPU architecture. The size of pointers in C is 

  • 8 bytes for a 64-bit System
  • 4 bytes for a 32-bit System

The reason for the same size is that the pointers store the memory addresses, no matter what type they are. As the space required to store the addresses of the different memory locations is the same, the memory required by one pointer type will be equal to the memory required by other pointer types.

How to find the size of pointers in C?

We can find the size of pointers using the sizeof operator as shown in the following program:

Example: C Program to find the size of different pointer types.

C
// C Program to find the size of different pointers types
#include <stdio.h>

// dummy structure
struct str {
};

// dummy function
void func(int a, int b){};

int main()
{
    // dummy variables definitions
    int a = 10;
    char c = 'G';
    struct str x;

    // pointer definitions of different types
    int* ptr_int = &a;
    char* ptr_char = &c;
    struct str* ptr_str = &x;
    void (*ptr_func)(int, int) = &func;
    void* ptr_vn = NULL;

    // printing sizes
    printf("Size of Integer Pointer  \t:\t%d bytes\n",
           sizeof(ptr_int));
    printf("Size of Character Pointer\t:\t%d bytes\n",
           sizeof(ptr_char));
    printf("Size of Structure Pointer\t:\t%d bytes\n",
           sizeof(ptr_str));
    printf("Size of Function Pointer\t:\t%d bytes\n",
           sizeof(ptr_func));
    printf("Size of NULL Void Pointer\t:\t%d bytes",
           sizeof(ptr_vn));

    return 0;
}

Output
Size of Integer Pointer      :    8 bytes
Size of Character Pointer    :    8 bytes
Size of Structure Pointer    :    8 bytes
Size of Function Pointer    :    8 bytes
Size of NULL Void Pointer    :    8 bytes

As we can see, no matter what the type of pointer it is, the size of each and every pointer is the same.

Now, one may wonder that if the size of all the pointers is the same, then why do we need to declare the pointer type in the declaration? The type declaration is needed in the pointer for dereferencing and pointer arithmetic purposes.

C Pointer Arithmetic

The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on a pointer. It is slightly different from the ones that we generally use for mathematical calculations as only a limited set of operations can be performed on pointers. These operations include:

  • Increment in a Pointer
  • Decrement in 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 of the same type.
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 = 0x7ffcfe7a77a0

Value of *ptr = 100
Value of ptr = 0x7ffcfe7a77a4

Value of *ptr = 200
Value of ptr = 0x7ffcfe7a77a8

C Pointers and Arrays

In C programming language, pointers and arrays are closely related. 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.

If we assign this value to a non-constant pointer of the same type, then we can access the elements of the array using this pointer.

Example 1: Accessing Array Elements using Pointer with Array Subscript

relationship between array and pointer

C
// C Program to access array elements using pointer
#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

Not only that, as the array elements are stored continuously, we can pointer arithmetic operations such as increment, decrement, addition, and subtraction of integers on pointer to move between array elements.

Example 2: Accessing Array Elements using Pointer Arithmetic

accessing array elements using pointer arithmetic

C
// C Program to access array elements using pointers
#include <stdio.h>

int main()
{

    // defining array
    int arr[5] = { 1, 2, 3, 4, 5 };

    // defining the pointer to array
    int* ptr_arr = arr;

    // traversing array using pointer arithmetic
    for (int i = 0; i < 5; i++) {
        printf("%d ", *ptr_arr++);
    }
    return 0;
}

Output
1 2 3 4 5 

This concept is not limited to the one-dimensional array, we can refer to a multidimensional array element as well using pointers.

To know more about pointers to an array, refer to this article – Pointer to an Array

Uses of Pointers in C

The C pointer is a very powerful tool that is widely used in C programming to perform various useful operations. It is used to achieve the following functionalities in C:

  1. Pass Arguments by Reference
  2. Accessing Array Elements
  3. Return Multiple Values from Function
  4. Dynamic Memory Allocation
  5. Implementing Data Structures
  6. In System-Level Programming where memory addresses are useful.
  7. In locating the exact value at some memory location.
  8. To avoid compiler confusion for the same variable name.
  9. To use in Control Tables.

Advantages of Pointers

Following are the major advantages of pointers in C:

  • Pointers are used for dynamic memory allocation and deallocation.
  • An Array or a 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 reduce the length of the program and its execution time as well.

Disadvantages of Pointers

Pointers are vulnerable to errors and have following disadvantages:

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

Conclusion

In conclusion, pointers in C are very capable tools and provide C language with its distinguishing features, such as low-level memory access, referencing, etc. But as powerful as they are, they should be used with responsibility as they are one of the most vulnerable parts of the language.

FAQs on Pointers in C

Q1. Define pointers.

Answer:

Pointers are the variables that can store the memory address of another variable.

Q2. What is the difference between a constant pointer and a pointer to a constant?

Answer:

A constant pointer points to the fixed memory location, i.e. we cannot change the memory address stored inside the constant pointer.

On the other hand, the pointer to a constant point to the memory with a constant value.

Q3. What is pointer to pointer?

Answer:

A pointer to a pointer (also known as a double pointer) stores the address of another pointer.

Q4. Does pointer size depends on its type?

Answer:

No, the pointer size does not depend upon its type. It only depends on the operating system and CPU architecture.

Q5. What are the differences between an array and a pointer?

Answer:

The following table list the differences between an array and a pointer:

Pointer

Array

A pointer is a derived data type that can store the address of other variables.An array is a homogeneous collection of items of any type such as int, char, etc.
Pointers are allocated at run time.Arrays are allocated at runtime.
The pointer is a single variable.An array is a collection of variables of the same type.
Dynamic in NatureStatic in Nature.

Q6. Why do we need to specify the type in the pointer declaration?

Answer:

Type specification in pointer declaration helps the compiler in dereferencing and pointer arithmetic operations.

Quizzes:



Similar Reads

Near, Far and Huge Pointers in C
In older times, the intel processors had 16-bit registers but the address bus was 20-bits wide. Due to this, the registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were used in C to store the addresses. There are old co
4 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: 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" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed. Example 1: C/C++ Code // C++ program to illustrate difference
5 min read
Right rotate given Array K times using Pointers
Given an array arr[] of size N and an integer K, the task is to right rotate the array K times. Examples: Input: arr[] = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5Explanation: After 1st rotation - {9, 1, 3, 5, 7}After 2nd rotation - {7, 9, 1, 3, 5} Input: {1, 2, 3, 4, 5, 6}, K = 2Output: 5 6 1 2 3 4 Approach: The naive approach and approach based on r
6 min read
How to Declare and Initialize an Array of Pointers to a Structure in C?
Prerequisite: Structure in CArray in C In C language, arrays are made to store similar types of data in contiguous memory locations. We can make arrays of either primitive data types, like int, char, or float, or user-defined data types like Structures and Unions. We can also make arrays of pointers in C language. Today we will learn how to create
8 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creati
3 min read
Passing Pointers to Functions in C
Prerequisites: Pointers in CFunctions in C Passing the pointers to the function means the memory location of the variables is passed to the parameters in the function, and then the operations are performed. The function definition accepts these addresses using pointers, addresses are stored using pointers. Arguments Passing without pointer When we
2 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
Why Does C Treat Array Parameters as Pointers?
In C, array parameters are treated as pointers mainly to, To increase the efficiency of codeTo save time It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array. The following two definit
2 min read
Difference between Arrays and Pointers
The array and pointers are derived data types that have lots of differences and similarities. In some cases, we can even use pointers in place of an array, and arrays automatically get converted to pointers when passed to a function. So, it is necessary to know about the differences between arrays and pointers to properly utilize them in our progra
7 min read
Difference between Iterators and Pointers in C++ with Examples
In C++ programming, we have both pointers and iterators that are used in managing and manipulating data structures. There are many similarities between iterators and pointers in their ability to reference and dereference memory, but there are certain differences between the two. Understanding the difference is very important in C++ programming. Poi
4 min read
Pointers vs Array in C++
Arrays and pointers are two derived data types in C++ that have a lot in common. In some cases, we can even use pointers in place of arrays. But even though they are so closely related, they are still different entities. In this article, we will study how the arrays and pointers are different from each other in C++. What is an Array?An array is the
3 min read
Applications of Pointers in C
Pointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers ApplicationThe following are some major applications o
4 min read
Array of Pointers in C
In C, a pointer array is a homogeneous collection of indexed pointer variables that are references to a memory location. It is generally used in C Programming when we want to point at multiple memory locations of a similar data type in our C program. We can access the data by dereferencing the pointer pointing to it. Syntax: pointer_type *array_nam
6 min read
Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples: Input: GeeksOutput: skeeGInput: GeeksForGeeksOutput: skeeGroFskeeGApproach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two p
2 min read
Dangling, Void , Null and Wild Pointers in C
In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deallocated memory), Void (pointing to some data locati
6 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and pointers are very similar as both are used to hav
5 min read
Output of C programs | Set 64 (Pointers)
Prerequisite : Pointers in C Question 1 : What will be the output of following program? [GFGTABS] C #include "stdio.h" int main() { char a[] = { 'A', 'B', 'C', 'D' }; char* ppp = &a[0]; *ppp++; // Line 1 printf("%c %c ", *++ppp, --*ppp); // Line 2 } [/GFGTABS]OPTIONS: a)C B b)B A c)B C d)C A O
3 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg