Pointers in C? with example | Declaring a pointer | Advantage of pointer | Usage of pointer

 

Pointers 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 size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.

Pointers in C


A pointer is a variable that stores the memory address of another variable. Pointers are used to manipulate and work with memory locations directly, making them a fundamental concept in C. Pointers are often used for tasks like dynamic memory allocation, passing data to functions by reference, and working with arrays and strings. They allow you to access and modify the data stored in memory locations.

Consider the following example to define a pointer which stores the address of an integer.

A pointer that stores the address of an integer in C
c
#include <stdio.h>

int main() {
int num = 42; // Declare an integer variable num with the value 42
int *ptr; // Declare a pointer to an integer

ptr = &num; // Assign the address of the num variable to the pointer ptr

// Accessing the value through the pointer
printf("Value of num: %d\n", *ptr);

return 0;
}

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer.

c
data_type *pointer_name;


Here's an example of declaring pointers for various data types.

c
int *intPtr; // Declaring an integer pointer
double *doublePtr; // Declaring a double (floating-point) pointer
char *charPtr; // Declaring a character pointer
struct MyStruct *structPtr; // Declaring a pointer to a user-defined structure


In each of these declarations, the * symbol indicates that you are declaring a pointer. 
The data_type specifies the type of data that the pointer will point to. 
The pointer_name is the name of the pointer variable.

Pointer Example

As you can see in the above figure, pointer variable stores the address of number variable, i.e., fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

here's an example of a C program using pointers with corresponding output.

c
#include <stdio.h>

int main() {
int num = 42; // Declare an integer variable 'num' with the value 42
int *ptr = &num; // Declare an integer pointer 'ptr' and assign the address of 'num'

printf("Value of num: %d\n", num); // Print the value of 'num'
printf("Address of num: %p\n", &num); // Print the address of 'num'
printf("Value of num via pointer: %d\n", *ptr); // Print the value of 'num' via the pointer
printf("Address stored in the pointer: %p\n", ptr); // Print the address stored in the pointer

// Modify the value through the pointer
*ptr = 100;
printf("New value of num: %d\n", num); // Print the updated value of 'num'

return 0;
}

Output:

yaml
Value of num: 42
Address of num: 0x7ffd4d43895c (the actual address may vary)
Value of num via pointer: 42
Address stored in the pointer: 0x7ffd4d43895c (the actual address may vary)
New value of num: 100

In this example:

We declare an integer variable num and initialize it to 42.
We declare an integer pointer ptr and assign the address of num to it.
We print the value of num, the address of num, the value of num via the pointer, and the address stored in the pointer.


Pointer to array

Here's how you can declare and use a pointer to an array:

c
#include <stdio.h> int main() { int arr[5] = {1, 2, 3, 4, 5}; // Declare an integer array int *ptr = arr; // Create a pointer to the array (points to the first element) printf("Elements of the array using a pointer:\n"); for (int i = 0; i < 5; i++) { printf("Element %d: %d\n", i, *(ptr + i)); } return 0; }


Output:

yaml
Elements of the array using a pointer: Element 0: 1 Element 1: 2 Element 2: 3 Element 3: 4 Element 4: 5


Pointer to a function

Here's how you can declare and use a pointer to a function:

c
#include <stdio.h> // A sample function int add(int a, int b) { return a + b; } int main() { int (*functionPtr)(int, int); // Declare a function pointer // Assign the address of the 'add' function to the function pointer functionPtr = add; // Call the function through the pointer int result = functionPtr(4, 5); printf("Result: %d\n", result); return 0; }


Output;

makefile
Result: 9

Pointer to structure

Let's say you have a structure named Person:

c
#include <stdio.h> // Define a structure struct Person { char name[50]; int age; }; int main() { // Declare a structure variable struct Person person; // Declare a pointer to a structure struct Person *personPtr; // Initialize the structure strcpy(person.name, "John"); person.age = 30; // Assign the address of the structure to the pointer personPtr = &person; // Access structure members using the pointer printf("Name: %s\n", personPtr->name); printf("Age: %d\n", personPtr->age); return 0; }


Output:

makefile
Name: John Age: 30

Advantage of pointer

1. Dynamic Memory Allocation: Pointers are crucial for dynamic memory allocation using functions like malloc, calloc, and realloc. This allows you to allocate memory as needed during runtime, making efficient use of resources.


2. Efficient Data Manipulation: Pointers provide direct access to memory locations, allowing for efficient manipulation of data in arrays, strings, and other complex data structures. This can improve performance in tasks like sorting, searching, and data processing.


3. Parameter Passing: Pointers enable you to pass variables to functions by reference, allowing you to modify the original data within the function. This is more efficient than passing large structures by value and avoids unnecessary copying of data.


4. Dynamic Data Structures: Pointers are fundamental for building dynamic data structures such as linked lists, trees, and graphs, as they allow you to create and manage data elements with varying sizes and structures.


5. Callback Functions: Function pointers enable you to implement callback mechanisms and create more flexible and modular code. This is commonly used for event handling and callback functions in libraries.



Usage of pointer

Pointers in C are used for various purposes, and their usage is fundamental to many aspects of C programming. Here are common use cases for pointers:


1. Dynamic Memory Allocation: Pointers are essential for allocating and managing memory at runtime using functions like malloc, calloc, and realloc. This is crucial for data structures that need to grow or shrink dynamically, such as arrays, linked lists, and dynamic strings.


2. Working with Arrays: Pointers are often used to iterate through and manipulate array elements efficiently. You can use pointer arithmetic to access and modify elements in an array.


3. Function Pointers: Function pointers enable you to create more flexible and modular code. They are commonly used for callback mechanisms, implementing function tables, and dynamic function dispatch.


Address Of (&) Operator

1. Obtaining the Address of a Variable: When you use the & operator followed by the name of a variable, it gives you the memory address where that variable is stored in the computer's memory.

For example:

c
int number = 42; int *ptr = &number; // Assigns the address of 'number' to the pointer 'ptr'
In this example, &number retrieves the address of the number variable, which is then stored in the ptr pointer.



2. Passing by Reference: The address-of operator is also used when you want to pass a variable to a function by reference, which allows the function to modify the original variable. This is common when you want to change the value of a variable within a function.

For example:

c
void modifyValue(int *valuePtr) { *valuePtr = 100; } int main() { int num = 42; modifyValue(&num); // Pass 'num' by reference printf("Modified value: %d\n", num); // Prints "Modified value: 100" return 0; }

In this example, the modifyValue function takes a pointer to an integer, and by passing &num, we pass the address of num to the function, allowing it to modify the original variable.


NULL Pointer

A NULL pointer is a pointer that doesn't point to any memory location. In C and C++, a NULL pointer is typically represented as a constant with the value 0. It's a special value used to indicate that a pointer does not reference a valid object or memory location.

Here's how a NULL pointer is used:

1. Initialization: You can initialize a pointer to NULL when you declare it, indicating that it doesn't currently point to any valid memory location.

c
int *ptr = NULL;

2. Checking for Validity: You often use NULL to check whether a pointer is valid before dereferencing it (accessing the data it points to). Dereferencing a NULL pointer can lead to undefined behavior and crashe.

c
int *ptr = NULL; if (ptr == NULL) { // Pointer is not valid, do something appropriate }

3. Return Values: Some functions, when they can't find a valid result, may return a NULL pointer to indicate that no valid result was found.
c
char *search(const char *key) { // If the key is not found, return a NULL pointer return NULL; }


Pointer Program to swap two numbers without using the 3rd variable.


c
#include <stdio.h> void swapWithoutThirdVariable(int *a, int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } int main() { int num1, num2; printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2); swapWithoutThirdVariable(&num1, &num2); printf("After swapping: num1 = %d, num2 = %d\n", num1, num2); return 0; }

Output:

mathematica
Enter two numbers: 10 20 Before swapping: num1 = 10, num2 = 20 After swapping: num1 = 20, num2 = 10

Reading complex pointers

There are several things which must be taken into the consideration while reading the complex pointers in C. Lets see the precedence and associativity of the operators which are used regarding pointers


1. Multi-Level Pointers: Multi-level pointers are pointers that point to other pointers. They are represented with additional asterisks for each level.

c
int num = 42; int *ptr1 = &num; int **ptr2 = &ptr1;

Here, ptr2 is a pointer to a pointer, and **ptr2 will access the value of num.

2. Pointers to Arrays: You can have pointers that point to arrays. These can be used to iterate through arrays or pass arrays to functions.

c
int arr[5] = {1, 2, 3, 4, 5}; int *ptr = arr; // Pointer to the first element of the array


3. Pointers to Structures: You can have pointers to structures to access and modify structure members.

c
struct Person { char name[50]; int age; }; struct Person person; struct Person *ptr = &person;

Now, ptr->name and ptr->age can be used to access and modify the structure members.


How to read the pointer: int (*p)[10].

The pointer int (*p)[10] is a pointer to an array of integers with 10 elements. To read and understand this pointer declaration, break it down as follows:

1. int: This indicates the data type that the pointer is pointing to. In this case, it's an integer.


2. (*p): The parentheses are used to specify the type of pointer. Here, it's a pointer to something.


3. [10]: This specifies the something the pointer is pointing to. It's an array with 10 elements.

So, int (*p)[10] is a pointer to an array of 10 integers. You can use this pointer to work with arrays of integers with 10 elements.

For example, you might declare an array of integers and then use a pointer of this type to point to that array:

c
int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int (*p)[10] = &myArray; // 'p' points to the array 'myArray'

Now, p is a pointer that points to the array myArray, allowing you to work with the array through the pointer p.

Post a Comment

0 Comments