Open In App

C Pointers

Last Updated : 23 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

A pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, it holds the address where the value is stored in memory. There are 2 important operators that we will use in pointers concepts i.e.

  • Dereferencing operator(*) used to declare pointer variable and access the value stored in the address.
  • Address operator(&) used to returns the address of a variable or to access the address of a variable to a pointer.

Example 1:

#include <stdio.h>

int main()
{

    // taking an integer variable
    int m = 100;

    // pointer variable ptr that stores
    // the address of variable m
    int *ptr = &m;

    // printing the value of variable m
    printf("The Value of Variable m is: %d\n", m);

    // printing the memory address of variable m
    // in hexadecimal format
    printf("The Memory Address of Variable m is: %p\n", &m);

    // printing the value of ptr i.e.
    // printing the memory address of variable m
    // in hexadecimal format using pointer variable
    printf("The Memory Address of Variable m is using ptr: %p\n", ptr);

    return 0;
}

Output
The Value of Variable m is: 100
The Memory Address of Variable m is: 0x7ffee1eea79c
The Memory Address of Variable m is using ptr: 0x7ffee1eea79c

Important Points:

  • %p format specifier is used to print the address stored in pointer variables.
  • Printing a pointer with %d format specifier may result in a warning or undefined behaviour because the size of a pointer (usually 4 or 8 bytes) may not match that of an integer.
  • The memory address format will always be in hexadecimal format(starting with 0x).
  • C does not use the term “reference” explicitly (unlike C++), “referencing” in C usually refers to obtaining the address of a variable using the address operator (&).
  • Pointers are essential for dynamic memory allocation, providing control over memory usage with functions like malloc, calloc, and free.

Example 2:

#include <stdio.h>

int main() {
  	
    // An integer variable
    int a = 10;

    // Create a pointer to integer (declaration)
    int * ptr;

    // Store the address of a inside pointer (initialization)
    ptr = &a;
  
  	// Print the content of ptr
  	printf("ptr = %p\n", ptr);

    // Get the value pointed by ptr (dereferencing)
    printf("*ptr = %d", *ptr);
  	
  	return 0;
}


Output

ptr = 0x7fffa0757dd4
*ptr = 10

The above demonstration can be understood by dividing it into three steps:

A. Pointer Declaration

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

B. Pointer Initialization

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

Note: We can also declare and initialize the pointer in a single step. This is called pointer definition.

C. 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.

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.

pointer-in-c

Example 3: C language stores provide a way to store the string as a pointer

#include <stdio.h>

int main() {
  
  	// Storing string as pointer
    char *s = "Geeks";

    printf("%s", s);
    return 0;
}

Output
Geeks

Types of Pointers in C

Pointers in C can be classified into many different types depending on the data it is pointing to:

1. Integer Pointers

As the name suggests, these are the pointers that point to the integer values. These pointers are pronounced as Pointer to Integer. Similarly, a pointer can point to any primitive data type and is named accordingly.

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.

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.

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.

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.

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.

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.

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

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.

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.

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

As 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.

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.

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/Decrement by 1
  • Addition/Subtraction of Integer
  • Subtracting Two Pointers of Same Type
  • Comparing/Assigning Two Pointers of Same Type
  • Comparing/Assigning with NULL

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 to array of the same type, then we can access the elements of the array using this pointer. Not only that, as the array elements are stored continuously, we can use pointer arithmetic operations such as increment, decrement, addition, and subtraction of integers on pointer to move between array elements.

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

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:

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

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

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.

What is pointer to pointer?

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

Does pointer size depends on its type?

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

What are the differences between an array and a pointer?

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.

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

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

Quiz:



Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg