Back to: C Tutorials For Beginners and Professionals
Pointer to Structure in C Language
In this article, I will discuss How to Access a Structure using a Pointer in C Language with Examples. We have already discussed the basics of Pointers and Structures in our previous articles.
How to Access a Structure Using a Pointer in C Language?
Let us see How to Access a Structure using a Pointer in C Language with an Example. First, we will see how to access the structure using normal variables, and then we will see how to access the structure using pointer variables using C language. Please look at the following example code where we access the structure using normal variables.
#include <stdio.h> struct Rectangle { int length; int breadth; }; int main () { struct Rectangle r = {10, 5}; r.length = 20; r.breadth = 30; }
As you can see in the above code, we have a structure Rectangle with two members, i.e., length and breadth. Inside the main method, we created a data variable of type structure (struct Rectangle r = {10, 5};) and assigned the length and breadth member values as 10 and 5. Then, we access the structure members (length and breadth) using the dot (.) operator, i.e. (r.length = 20; and r.breadth = 30;).
Now, let us see how to access the structure using a pointer. So, for this, first, we need to create a pointer of type structure, and then we need to initialize the pointer to the address of the structure variable as shown in the below two lines of code.
As you can see, the pointer variable type is struct Rectangle, so that it will hold the address of a structure variable further, if you notice the pointer variable holding the address of r.
Note: For every pointer, irrespective of the type, the pointer will take 2 bytes. Actually, it takes equal to the integer size in any compiler. If an integer takes 2 bytes, the pointer also takes 2 bytes. If an integer takes 4 bytes, the pointer also takes 4 bytes. Here, we are assuming the integer takes 2 bytes,
How to Access Structure Members Using a Pointer in C Language?
As of now, we have discussed two things. First, create a structure variable. Then, create a pointer variable of structure type and assign it to the structure address. Now, let us move and see the different ways to access the structure members using a pointer. We cannot access directly using the dot operator as follows:
p.length = 20;
p.breadth = 30;
This is because p is a pointer; it’s not a variable. The pointer holds the address, not the values directly. So, we need to go to the place where the pointer is pointing, i.e., to the base address of the structure variable r, and then access the data members. To do so, we must write the pointer using *, as shown below.
*p.length = 20;
*p.breadth = 30;
Again, this will also not work, and you will get an error. This is because the priority of the dot (.) operator is higher than the * operator. So, first, it will try to access the values, and hence, you will get the error. To overcome this error, put *p inside a bracket and then call the structure member as follows:
(*p).length = 20;
(*p).breadth = 30;
With the above changes in place, it will work as expected. We have to write this much code to access the structure members. Instead of this syntax, the C programming language gives a simple syntax for accessing the members using a pointer, as follows:
p -> length = 20;
p -> breadth = 30;
As you can see in the above, using the pointer variable and arrow (->) operator, we can access the members of a structure using a pointer in C language. The complete code is given below.
#include <stdio.h> struct Rectangle { int length; int breadth; }; int main () { struct Rectangle r = {10, 5}; struct Rectangle *p = &r; p -> length = 20; p -> breadth = 30; int Area = p -> length * p -> breadth; printf("%d",Area); }
How do you get the memory in a heap?
Now, one more thing we will do: we will create an object dynamically in the heap using a pointer. Here, we’ll dynamically create an object or a variable of type rectangle in the Heap memory. Let us discuss this step by step.
Step1: Create a pointer variable
First, we must create a pointer variable of type structure, as shown below. This pointer variable is created inside the stack frame of the main memory.
struct Rectangle *p;
Step2: Allocating Memory in Heap
We need to create the rectangle object or variable in the heap memory. As we already discussed, we need to use the Malloc function to create the memory in the heap. We need to specify the size we want in the heap memory for the malloc function. Here, size is nothing but the size of the structure. Again, the malloc function returns a void pointer, so we need to typecast the struct Rectangle pointer. The following line of code does the same.
p=(struct Rectangle *) malloc(sizeof (struct Rectangle));
The above line will allocate an object of type Rectangle in the heap.
Step3: Accessing the Members:
Now, you can access and modify the structure members using the arrow operator as follows:
p -> length=10;
p -> breadth=5;
The Complete code is given below.
#include <stdio.h> #include <stdlib.h> struct Rectangle { int length; int breadth; }; int main () { struct Rectangle *p; p=(struct Rectangle *) malloc(sizeof (struct Rectangle)); p -> length=10; p -> breadth=5; int Area = p -> length * p -> breadth; printf("%d", Area); }
Memory Representation:
The Pointer variable is created in the stack, the rectangle object is created in the heap, and the pointer points to the heap memory. For a better understanding, please have a look at the below image.
When to Use Pointer to Structure in C?
Using pointers to structures in C is a powerful technique that offers several advantages in specific scenarios. Here are some common situations where you might choose to use a pointer to a structure:
- Dynamic Memory Allocation: When you need to allocate memory for a structure dynamically. This is especially useful when the structure size is large or when the number of structures required is not known at compile time. For example, creating nodes in a linked list or entries in a hash table.
- Efficient Memory Usage: Pointers to structures can reduce memory usage. Instead of passing the whole structure to functions, you can pass a pointer to the structure, which is typically smaller in size, especially for large structures.
- Modifying Structure in Functions: If you want to modify the structure in a function and have the changes reflected outside the function, you use pointers. Passing a pointer allows the function to modify the original structure, not just a copy.
- Implementing Complex Data Structures: Pointers to structures are essential in implementing complex data structures like linked lists, trees, graphs, etc., where each element needs to reference other elements.
- Memory Management Flexibility: Pointers offer more flexibility in memory management. You can allocate and deallocate memory as needed, which is crucial in applications with varying memory requirements.
- Interfacing with Hardware or External Systems: In low-level programming, such as device drivers or embedded systems, pointers to structures are often used to represent and manipulate hardware registers or structured data received from external systems.
- Efficient Data Passing in APIs: When designing libraries or APIs in C, using pointers to structures as function parameters can lead to more efficient and cleaner code, especially when structures are large or complex.
Pointer to Structure in C Language Real-Time Examples:
In C programming, pointers can be used to point to structures, just like they can point to any other data type. This can be particularly useful for passing structures to functions, manipulating complex data structures, and in systems programming. Here are some examples illustrating how you can use pointers to structures in C.
Basic Structure Definition
First, let’s define a simple structure:
struct Person { char name[50]; int age; };
Example 1: Creating and Accessing a Structure via Pointer
#include <stdio.h> #include <string.h> int main() { struct Person person; struct Person *ptr; // Pointing ptr to person ptr = &person; // Accessing structure members using pointer strcpy(ptr->name, "Alice"); // Using -> operator ptr->age = 30; printf("Name: %s\n", ptr->name); printf("Age: %d\n", ptr->age); return 0; }
In this example, ptr->name and ptr->age are used to access the name and age fields of the person structure.
Example: Dynamic Memory Allocation of Structure
You can dynamically allocate a structure and use a pointer to access it.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct Person *ptr; // Dynamically allocate memory for a Person structure ptr = (struct Person *)malloc(sizeof(struct Person)); if (ptr != NULL) { strcpy(ptr->name, "Bob"); ptr->age = 25; printf("Name: %s\n", ptr->name); printf("Age: %d\n", ptr->age); // Free allocated memory free(ptr); } return 0; }
This example demonstrates how to dynamically allocate memory for a structure using malloc and free it using free.
Example: Passing Structure Pointer to Function
Passing a pointer to a structure to a function can be more efficient than passing the structure by value, especially for large structures.
#include <stdio.h> #include <string.h> void printPerson(struct Person *p) { printf("Name: %s\n", p->name); printf("Age: %d\n", p->age); } int main() { struct Person person; strcpy(person.name, "Charlie"); person.age = 28; // Passing address of person to the function printPerson(&person); return 0; }
In this example, printPerson is a function that takes a pointer to a Person structure. We pass the address of the person to this function.
Note: Always remember to free the memory allocated with malloc to avoid memory leaks. Using pointers to structures is very common in C, especially when dealing with dynamic data structures like linked lists, trees, and more complex data structures.
Complex Data Structures Example Using Pointer to Structure in C
Creating complex data structures in C often involves using pointers to structures, especially when dealing with linked data structures like linked lists, trees, or graphs. Here’s an example of a doubly linked list implemented in C using pointers to structures. This example demonstrates how you can build and manipulate a complex data structure.
Step 1: Define the Node Structure
First, define the structure of a node in the doubly linked list.
#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; struct Node* prev; } Node;
Step 2: Function to Create a New Node
A utility function to create a new node.
Node* createNode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; newNode->prev = NULL; return newNode; }
Step 3: Function to Insert at the Head
Function to insert a new node at the beginning of the list.
void insertAtHead(Node** head, int data) { Node* newNode = createNode(data); newNode->next = *head; if (*head != NULL) { (*head)->prev = newNode; } *head = newNode; }
Step 4: Function to Print the List
Function to print the list from the head.
void printList(Node* head) { Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); }
Step 5: Main Function to Demonstrate
Using these functions to create and manipulate a doubly linked list.
int main() { Node* head = NULL; insertAtHead(&head, 3); insertAtHead(&head, 2); insertAtHead(&head, 1); printf("Doubly Linked List: "); printList(head); // Further operations like insertion, deletion, etc. can be added here return 0; }
Explanation of the Above Program:
- Node Structure: Each node has data, a pointer to the next node, and a pointer to the previous node.
- createNode Function: Allocates memory for a new node, initializes its data, and sets its next and previous pointers to NULL.
- insertAtHead Function: Inserts a new node at the beginning of the list. It adjusts the next and prev pointers appropriately.
- printList Function: Iterates over the list starting from the head and prints each element’s data.
Output
When you run this program, it will create a doubly linked list with three nodes and print:
Doubly Linked List: 1 2 3
This example demonstrates a fundamental complex data structure using pointers to structures in C. From here, you could extend the functionality by adding more operations like deleting nodes, searching for elements, or inserting at different positions in the list.
In the next article, I will discuss How to pass an Array as a Parameter to a function in C Language with Examples. In this article, I explain How to access Structure using Pointers in C Language with Examples. I hope you enjoy this article, “How to Access a Structure using a Pointer in C Language.”.