Pointers in C: Unlocking the Secrets of Memory with Examples

Updated on September 27, 2024

Article Outline

A pointer is a variable that stores the address of another variable of the same type. Pointers are said to be difficult but are probably the most important tools for any programmer. Knowing pointers will unlock several secrets in memory management, improve performance, and allow better data handling.

Pointers in C

Pointers are variables that store the memory address of other variables. It allows developers to directly access and manipulate data in memory. They are declared by specifying the data type followed by an asterisk (e.g., int *ptr). It indicates that the pointer points to an integer. Pointers can be initialized using the address.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Syntax of Pointers in C

The syntax of Pointers in C is:

 

Data_type *pointer_variable_name

 

Some of the valid pointer declarations in C are as follows:

int    *ptr_in; char   *ptr_ch ; double *ptr_dbl; float  *ptr_fl;

How to Use Pointers in C?

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

 

  • Pointer Declaration
  • Pointer Initialization
  • Pointer Dereferencing

Pointer Declaration

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

 

Example

int *ptr ;

The pointer declared here will point to some random memory address as it is not initialized.  This pointer is called a wild pointer.

Pointer Initialization

 

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

 

Example

int var =  500  ; int  *ptr ; ptr  = &var ;

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

Pointer Dereferencing

It is the process of accessing the value stored at the memory address that the pointer points to. In Programming languages like C or C++, a pointer is a variable that holds the address of another variable. For Example, Suppose we have an integer variable x with a value of 10. We can declare a pointer p that points to its address using the address-of operator &

Pointers in C

 

Program

#include <stdio.h> void pointer_declaration(){ int var = 340; int* ptr; ptr = &var; 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(){ pointer_declaration(); return 0; }

Output

Value at ptr = 0x7ffd597049d4 Value at var = 340 Value at *ptr = 340

Types of Pointers in C

In C language, we can define pointers into many different types based on the parameters we use to define them.

Integer Pointers

 

This pointer stores the type of pointers that point to the integer values.

 

Syntax

int *ptr #include <stdio.h> int main() { int value = 343; int *pointer = &value; printf("Value: %dn", *pointer); *pointer = 100; // Print the modified value printf("Modified Value: %dn", value);   return 0; }  

Output

Value: 343 Modified Value: 100

Array Pointer

An array pointer points to the first element of an array. Understanding array pointers is essential for working with dynamic data structures like LinkedList, Stack, Tree, etc. It is also known as the Pointer to Arrays. We can create a pointer to an array using the given syntax.

char *ptr = &array_name ; // Array Pointer in C language #include <stdio.h> int main(){ int arr[] ={ 30,50,90,38,90}; int *ptr = arr ;   for(int i =0;i<5;i++){ printf("%d ", *(ptr +i)) ; } return 0 ; }

Output

30 50 90 38 90

Structure Pointer

This pointer points to the structure type, called a Structure Pointer or a Pointer to Structure. It can be declared in the same way as the other primitive data types.

 

struct struct_name *ptr

 

In C language, the  structure pointers are used in the data structure, such as linked lists, trees, etc

#include <stdio.h> #include <string.h> struct Student { char name[50]; int age; float grade; }; int main() { struct Student student1; strcpy(student1.name, "Alice"); student1.age = 20; student1.grade = 85.5; struct Student *ptr = &student1; printf("Student Name: %sn", ptr->name); printf("Student Age: %dn", ptr->age); printf("Student Grade: %.2fn", ptr->grade); ptr->age = 21; ptr->grade = 90.0; printf("nUpdated Student Age: %dn", ptr->age); printf("Updated Student Grade: %.2fn", ptr->grade);   return 0; }

Output

Student Name: Alice Student Age: 20 Student Grade: 85.50 Updated Student Age: 21 Updated Student Grade: 90.00

Function Pointers

It is a powerful feature that allows you to store a function’s address in a pointer variable. This enables dynamic function calls, callbacks, and more flexible code structures. The program below demonstrates function pointers in the C language.  

 

Syntax

int (*ptr) (int, char) ; #include <stdio.h> int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } typedef int (*operationFunc)(int, int); void performOperation(operationFunc op, int x, int y) { printf("Result: %dn", op(x, y)); } int main() { operationFunc funcPtr; funcPtr = add; printf("Using add function:n"); performOperation(funcPtr, 5, 3); funcPtr = subtract; printf("Using subtract function:n"); performOperation(funcPtr, 5, 3); return 0; }

Output

Using add function: Result: 8 Using subtract function: Result: 2

Double Pointer

In C language, a pointer variable can store the memory addressof another pointer. It is called the double-pointer in C language. Instead of pointing to a data value, it points to another pointer.

Syntax

 

datatype  ** pointer_name ;

// Double Pointer in C language int main(){ int num =  50 ; int *num2 = num ; int **num3 = num2 ; printf("Output = %d",num) ; printf("Output2 = %d",*(num2)) ; printf("Output3 = %d", **(num3)) ; return 0 ; }

Output

Values: 10 20 30

NULL Pointer

The NULL Pointers are those pointers that do not point to any memory location in the computer memory. It can be assigning a NULL value to the pointer. This pointer type can be assigned any value, such as a NULL value.

Syntax

 

data_type *pointer_name = NULL

 

Or

 

pointer_ame = NULL

 

It is always a good practice to assign NULL to the pointer that is not currently used in the program.

#include <stdio.h> void checkPointer(int *ptr) { if (ptr == NULL) { printf("Pointer is NULL. Cannot dereference it.n"); } else { printf("Pointer value: %dn", *ptr); } } int main() { int *ptr1 = NULL; int value = 42; int *ptr2 = &value; checkPointer(ptr1); checkPointer(ptr2); return 0; }

Output

Pointer is NULL. I cannot dereference it. Pointer value: 42

Void Pointer 

In the C language, a void type pointer means that it does not have an associated data type. It is also called generic pointers, which can point to any type and be typecasted to any type.  

 

Syntax  

 

void *pointer_name  

Wild Pointers

This type of pointer has not been initialized with something yet. When a C developer dereferencing a wild pointer has undefined behavior that may crash the program or give a garbage value.

 

Example

 

int *ptr ;

char *str;

#include <stdio.h> int main() { int *ptr; printf("Attempting to dereference a wild pointer:n"); int value = 42; ptr = &value; printf("Value after initialization: %dn", *ptr); return 0; }  

Output

Attempting to dereference a wild pointer: Value after initialization: 42

Constant Pointers

Once defined, the constant pointer stored inside the pointer cannot be modified. It will always point to the same memory address.

data_type *const pointer_name ;

#include <stdio.h> int main() { int value = 42; int anotherValue = 100; int *const ptr = &value; printf("Value pointed to by ptr: %dn", *ptr); *ptr = 50; printf("New value pointed to by ptr: %dn", *ptr); printf("Original value: %dn", value); return 0; }

Output

New value pointed to by ptr: 50 Original value: 50

Other Types of Pointers in C

Apart from those specified above, the following types of pointers are also available to use in C language.

 

  • Far Pointer: This pointer is typically 32-bit and can access memory outside the current segment.
  • Dangling Pointer: A dangling pointer is a pointer to a memory location that has been deleted or freed.
  • Huge Pointer: The huge pointer is 32-bit long, counting segment and offset addresses.
  • Near Pointer: It stores 16-bit addresses within the current segment on a 16-bit machine.
  • Normalized Pointer: It is a 32-bit pointer that has as much of its value in the segment register as possible.
  • File Pointer: This pointer to a FILE data type is called a stream pointer or a file pointer

Benefits of Using Pointers in C

The C language offers several benefits that enhance the language’s functionality and performance.

 

  • Memory Access: Pointer allows direct access to memory locations, enabling efficient data manipulation.
  • Memory Management: Pointers facilitate dynamic memory allocation programs to use memory more flexibly based on runtime needs.
  • Data Structures: It is essential for implementing complex data structures like linked lists, trees, and graphs, allowing dynamic connections between
  • Accessing Hardware: Pointers are often used to access the hardware system programming to interact directly with hardware and memory-mapped devices.

 

Also Read: Power Function in C

Conclusion

Pointers in C are among the most powerful features that unlock memory management and manipulation secrets. They enable direct access to memory addresses, thus permitting dynamic memory allocation and efficient data handling through pointers. Pointers might have been applied to accomplish complex data structures, optimum function performance, and low-level operations in systems programming, but with great power comes great responsibility. Careful use of pointers is necessary to avoid common pitfalls, such as memory leaks and undefined behavior.

FAQs
A pointer is a variable that stores the memory address of another variable. It allows direct manipulation of that variable’s memory.
A null pointer is a pointer that does not point to any valid memory location. It is often initialized with NULL to signify that it is not currently pointing to a valid object.
You use the free function to deallocate memory that was previously allocated using malloc, calloc, or realloc for example, free(ptr).

Updated on September 27, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved