C Pointers Concept Syntax And Examples

It has the following syntax:

Example

data_type *var_name;

In this particular format,

  • data_type: Indicates the specific data type being referenced by the pointer.
  • var_name: Denotes the name assigned to the pointer.

Examine the subsequent instance to declare a pointer that holds the memory location of an integer.

Example

int n = 10;   

int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.

Declaring a pointer

A pointer in the C programming language is typically defined with the * (asterisk symbol). This type of pointer, also referred to as an indirection pointer, is essential for dereferencing pointers in C.

Example

int *a; //pointer to int  

char *c; //pointer to char

Accessing Address to Pointers

In C++, the utilization of pointers to access memory addresses is a fundamental concept that allows for effective manipulation of memory and the creation of dynamic data structures like arrays, linked lists, trees, and more. The addressof operator (&) is primarily employed to save the memory address of a variable, which can then be assigned to a pointer variable for initialization purposes.

Example

int num = 32;

int *ptr = #

Dereference a Pointer

Accessing the pointer directly will solely yield the memory location stored within it. For example,

Example

Example

#include <stdio.h>

int main() {  //main function

    int num = 42;         

    int *ptr = #      

    printf("Value of num using pointer: %d\n", *ptr);

    *ptr = 28;

    printf("New value of num after dereferencing: %d\n", num);

    return 0;

}

Output:

Output

Value of num using pointer: 42

New value of num after dereferencing: 28

Explanation:

In this instance, an integer variable named num is initialized to 42, and a pointer named ptr is assigned the memory address of num. Subsequently, it displays the contents of num using the pointer (*ptr), updates num's value to 28 by dereferencing, and then showcases the modified value.

We must initially dereference the pointer in order to retrieve the value stored at the memory location. This task is accomplished using the dereferencing operator (*).

C Another Pointer Example

Let's consider another instance to demonstrate the concept of pointers in the C programming language.

Example

Example

#include<stdio.h>  

int main(){    //using main function

int number=50;    

int *p;      

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

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

printf("Value of p variable is %d \n", *p);   

return 0;  

}

Output:

Output

Address of p variable is d86801c 

Value of p variable is 50

Explanation:

In this code snippet, a pointer labeled p is primarily employed to hold the memory location of the variable named number. Subsequently, the *p operator is used to dereference the pointer and retrieve the data stored at that specific location. To conclude, it displays both the memory address and the value of the number by leveraging the pointer.

Pointer to array

In the realm of C programming, a pointer to an array is a specific type of pointer designed to hold the memory address of the initial array element. This pointer can be employed to interact with and modify the array elements through the mechanism of pointer arithmetic.

C Pointer to an Array Example

Let's consider an example to demonstrate a pointer to an array in C programming.

Example

Example

#include <stdio.h>

int main() {   //main function

    int arr[5] = {10, 20, 30, 40, 50};

    int (*ptr)[5] = &arr;  

    printf("First element: %d\n", (*ptr)[0]);

    printf("Second element: %d\n", (*ptr)[1]);

    return 0;

}

Output:

Output

First element: 10

Second element: 20

Explanation:

In this instance, we are establishing an integer array and a pointer called ptr that points to the complete array. Subsequently, the program displays and retrieves elements using (*ptr)[index].

Pointer to a function

In C programming, a function pointer is employed to hold the memory address of a function. This mechanism enables us to invoke the function indirectly, proving advantageous for scenarios like callbacks, dynamic function calls, and passing functions as arguments.

Syntax

It has the following syntax:

Example

void show (int);  

void(*p)(int) = &display; // Pointer p is pointing to the address of a function

C Pointer to a Function Example

Let's consider an example to demonstrate the concept of a function pointer in the C programming language.

Example

Example

#include <stdio.h>

int add(int a, int b) {

    return a + b;

}

int main() {  //main function

    int (*funcPtr)(int, int);  

    funcPtr = add;             

    int result = funcPtr(7, 3); 

    printf("Result: %d\n", result);

    return 0;

}

Output:

Output

Result: 10

Explanation:

In this instance, we define a function named add and invoke it using a function pointer called functor. Subsequently, the pointer retains the memory address of the add function, enabling the function to be executed via the pointer.

Pointer to Structure

In the C programming language, utilizing a pointer to a structure allows for accessing the members of the structure via dynamic memory allocation. This technique is commonly applied in conjunction with dynamic data structures like trees, linked lists, and various other data structures.

Syntax

It has the following syntax:

Example

struct st {  

    int i;  

    float f;  

}ref;  

struct st *p = &ref;

C pointer to a Structure Example

Let's consider an example to demonstrate a pointer to a structure in the C programming language.

Example

Example

#include <stdio.h>

struct Student {

    char name[20];

    int age;

};

int main() {   //main function

    struct Student s1 = {"Johnty", 20};

    struct Student *ptr = &s1;

    printf("Name: %s\n", ptr->name);

    printf("Age: %d\n", ptr->age);

    return 0;

}

Output:

Output

Name: Johnty

Age: 20

Explanation:

In this instance, we define a construct called Student and an instance named s1. Subsequently, a pointer ptr is assigned the memory location of s1, allowing access to the structure's elements through ptr->name and ptr->age for displaying their respective values.

Size of Pointers

The size of a pointer in C is determined by the architecture of the machine (bit system) rather than iLogic Practices. Typically, in a 32-bit system, all pointers occupy 4 bytes. Conversely, in a 64-bit machine, all pointers typically require 8 bytes of memory.

The dimensions remain constant regardless of the data type (int, char, float*, etc.). Verification can be done using the sizeof operator.

The rationale behind the identical space allocation is that pointers retain memory addresses regardless of their data type. Due to the consistent space required for storing memory locations' addresses, the space utilized by a particular pointer type will mirror that of other pointer types.

Size of Pointers Example

Let's consider a demonstration to showcase the magnitude of pointers in the C programming language.

Example

Example

#include <stdio.h>

int main() {  //main function

    int *intPtr;

    float *floatPtr;

    char *charPtr;

    double *doublePtr;

    printf("Size of inLogic Practiceer: %zu bytes\n", sizeof(intPtr));

    printf("Size of floaLogic Practiceer: %zu bytes\n", sizeof(floatPtr));

    printf("Size of char pointer: %zu bytes\n", sizeof(charPtr));

    printf("Size of double pointer: %zu bytes\n", sizeof(doublePtr));

    return 0;

}

Output:

Output

Size of inLogic Practiceer: 8 bytes

Size of floaLogic Practiceer: 8 bytes

Size of char pointer: 8 bytes

Size of double pointer: 8 bytes

Explanation:

In this instance, we define pointers of different data kinds and display their sizes using the sizeof operator. Subsequently, it highlights that the size of a pointer is contingent on the system, irrespective of the type it points to.

Addressof (&) Operator

The address-of operator '&' is utilized to retrieve the memory location of a variable. Nevertheless, we must employ %u to showcase the address of a variable.

C Addressof (&) Operator Example

Let's consider an example to demonstrate the usage of the addressof (&) operator in the C programming language.

Example

Example

#include<stdio.h>  

int main(){    //main function

int number=50;   

printf("value of number is %d, address of number is %u",number,&number);    

return 0;  

}

Output:

Output

value of number is 50, address of number is 2617052868

Special Types of Pointers

There are four distinct pointer types that are utilized or mentioned in different scenarios:

1) NULL Pointer

In C programming, a pointer without any assigned value except NULL is referred to as the NULL pointer. When declaring a pointer without a specific address, assigning a NULL value is a recommended practice for better clarity and handling.

Syntax

It has the following syntax:

Example

int *p=NULL;

In many libraries, the pointer's value defaults to 0 (zero).

2) Void Pointer

In the realm of C programming, void pointers are a category of pointers that do not have any specific data type linked to them. They are commonly known as generic pointers since they have the ability to reference any data type and can be casted to any desired type.

C Void Pointer Example

Let's consider a scenario to demonstrate the concept of a null pointer in the C programming language.

Example

Example

#include <stdio.h>

int main() {   //main function

    int a = 21;

    float b = 3.74;

    void *ptr;

    ptr = &a;

    printf("Value of a using void pointer: %d\n", *(int *)ptr);

    ptr = &b;

    printf("Value of b using void pointer: %.2f\n", *(float *)ptr);

    return 0;

}

Output:

Output

Value of a using void pointer: 21

Value of b using void pointer: 3.74

Explanation:

In this instance, a void pointer named ptr is employed to store the memory location of an integer followed by a floating-point number. Subsequently, the pointer is cast to the respective data types in order to dereference it and display the values of 'a' and 'b'.

3) Wild Pointers

In C programming, uninitialized pointers, also known as wild pointers, are pointers that have not been initialized or assigned any specific value yet. These particular pointers can pose challenges in our programs and may result in program crashes. Modifying values using wild pointers can potentially cause data aborts or corruption.

4) Dangling Pointer

In the C programming language, a pointer pointing to a memory location that has been deallocated (or freed) is known as a dangling pointer. This situation can lead to unpredictable program behavior and is a common source of bugs in C programs.

C Dangling Pointer Example

Let's consider an instance to demonstrate the concept of a dangling pointer in the C programming language.

Example

Example

#include <stdio.h>

#include <stdlib.h>

int main() {   //main function

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

    *ptr = 50;

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

    free(ptr);  

    printf("Memory has been freed");

    ptr = NULL; 

    return 0;

}

Output:

Output

Value: 50

Memory has been freed

Explanation

In this instance, we allocate memory dynamically for an integer, set a value to it, display the value, and subsequently release the allocated memory. After freeing the memory, the pointer is also assigned to NULL to prevent it from becoming a dangling pointer.

How to Use Pointers for Dynamic Memory Allocation

Dynamic memory allocation in C is a powerful use case for pointers as it allows for the allocation of memory at execution time as opposed to compile time.

We allocate memory dynamically by utilizing the malloc function, which provides a pointer to the allocated memory space. For example:

Example

Example

#include <stdio.h>

#include <stdlib.h>

int main() {  //main function

    int *ptr;

    int n, i;

    printf("Enter the number of elements: ");

    scanf("%d", &n);

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

    if (ptr == NULL) {

        printf("Memory allocation failed!\n");

        return 1;

    }

    printf("Enter %d integers:\n", n);

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

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

    }

    printf("The integers are:\n");

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

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

    }

    free(ptr);  

    return 0;

}

Output:

Output

Enter the number of elements: 33 

Enter 3 integers:

95

32

16

The integers are:

95 32 16

Explanation:

In this instance, we dynamically reserve memory for an array of integers by using a pointer and the malloc function. Following this, the program receives input from the user, displays the entered values, and then deallocates the memory using free to avoid memory leaks.

C Pointer Arithmetic

The arithmetic operations that can be done on a pointer are known as the pointer arithmetic. They are not the same as the operations we normally use for mathematical calculations since limited operations can be done on pointers. Those operations include:

  • Increment/Decrement
  • Addition/Subtraction of Integer
  • Subtracting Two Pointers of the Same Type
  • Comparing/Assigning Two Pointers of the Same Type
  • Comparing/Assigning with NULL
  • Multilevel Pointers

In the C programming language, it is possible to generate pointers with multiple levels such as - ptr3, ptr4, ***ptr5, and so on. Among these, the double pointer (pointer to pointer) is frequently utilized. This type of pointer stores the memory address of another pointer. Instead of referencing a specific data value, double pointers point to yet another pointer.

C Multilevel Example

Let's consider an example to demonstrate the concept of multilevel pointer in the C programming language.

Example

Example

#include <stdio.h>

int main() {   //main function

    int num = 100;

    int *ptr1 = #      

    int **ptr2 = &ptr1;    

    printf("Value of num: %d\n", num);

    printf("Value using ptr1: %d\n", *ptr1);

    printf("Value using ptr2: %d\n", **ptr2);

    return 0;

}

Output:

Output

Value of num: 100

Value using ptr1: 100

Value using ptr2: 100

Explanation:

In this instance, a pointer named ptr1 is employed to store the memory address of num, while another pointer named ptr2 is utilized to store the memory address of ptr1. Subsequently, it displays the value of num both directly, indirectly through ptr1, and indirectly through ptr2 by utilizing double dereferencing.

ConstanLogic Practiceers

In constantLogic Practiceers, the memory address contained in the pointer remains fixed and immutable once it's initialized. The pointer will consistently reference the same memory location.

C ConstanLogic Practiceer Example

Let's consider an example to demonstrate the use of constants in C programming.

Example

Example

#include <stdio.h>

int main() {  //main function

    int a = 10, b = 20;

    int *const ptr = &a;  

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

    *ptr = 15;   

    printf("Updated Value: %d\n", *ptr);

    return 0;

}

Output:

Output

Value: 10

Updated Value: 15

Explanation:

In this instance, we declare a constant pointer named ptr that points to an integer variable a. Subsequently, it displays the value that ptr is pointing to, modifies this value using *ptr, and then showcases the updated value. It's important to note that the pointer ptr is fixed to point to the same memory location and cannot be reassigned to point to a different variable like b.

Advantage of Pointer

There are several advantage of pointer in C programming. Some of them are as follows:

  • In C programming, a pointer reduces the code and improves the performance. It is used to retrieve strings, trees, etc. and used with arrays, structures, and functions.
  • We can return multiple values from a function using the pointer.
  • It allows us to access any memory location in the computer's memory.
  • Pointer Program to swap two numbers without using the 3rd Variable

Let's consider an illustration demonstrating how to exchange two numbers without utilizing a third variable in the C programming language.

Example

Example

#include<stdio.h>  

int main(){    //main function

int a=10,b=20,*p1=&a,*p2=&b;  

printf("Before swap: *p1=%d *p2=%d",*p1,*p2);  

*p1=*p1+*p2;  

*p2=*p1-*p2;  

*p1=*p1-*p2;  

printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);  

return 0;  

}

Output:

Output

Before swap: *p1=10 *p2=20

After swap: *p1=20 *p2=10

Usage of pointer

There are numerous uses of pointers in the C programming language. Some examples include:

  • Dynamic Memory Allocation: In C, dynamic memory allocation can be achieved through the malloc and calloc functions, leveraging pointers.
  • Arrays, Functions, and Structures: Pointers play a vital role in arrays, functions, and structures within C. They help streamline code and enhance overall performance.
  • Problems with Pointers

Pointers are prone to errors and have the following drawbacks:

  • Memory can be corrupted if a wrong value is passed to pointers.
  • Pointers are slightly harder to learn.
  • Pointers are primarily the cause of memory leaks in C.
  • Using pointers for access is relatively slower than variables in C.
  • Uninitialized pointers may result in a segmentation fault.

Input Required

This code uses input(). Please provide values below: