Back to: C Tutorials For Beginners and Professionals
Structure using Pointer in C Language with Examples
In this article, I will discuss the Structure using Pointer in C Language with Examples. Please read our previous article discussing Nested Structure in C Language with Examples.
Structure Using Pointer in C
Combining structures with pointers in C programming can be a powerful way to manage and manipulate data. Let’s explore how structures and pointers work together, along with key concepts and examples.
Structures in C
A structure in C is a user-defined data type that allows you to combine data items of different kinds. Structures are used to represent a record. Suppose you want to keep track of books in a library. You might want to track the following attributes of each book:
- Title
- Author
- Subject
- Book ID
In C, a structure for a book might look like this:
struct Book { char title[50]; char author[50]; char subject[100]; int book_id; };
Pointers in C
A pointer in C is a variable that stores the memory address of another variable. Pointers are used for various purposes in C, such as dynamic memory allocation, arrays, and function arguments.
Combining Structures and Pointers in C Language:
When you combine structures and pointers, you get a powerful tool for data management. You can create a pointer that points to a structure. This allows you to access the structure’s members without creating a copy of the structure.
Declaring and Initializing Structure Pointers in C
You declare a pointer to a structure in the same way you declare a pointer to any other data type. You must use the struct keyword followed by the structure name. Here’s how you can declare and initialize a structure pointer:
struct Book book1; struct Book *pointer; pointer = &book1;
Accessing Structure Members Through Pointers
To access the members of a structure using a pointer, you use the arrow operator (->). This is equivalent to dereferencing the pointer to access the structure and then accessing the member.
strcpy(pointer->title, "C Programming"); pointer->book_id = 6495407;
Example: Structure using Pointer in C
Here is the full example that combines all these concepts:
#include <stdio.h> #include <string.h> struct Book { char title[50]; char author[50]; char subject[100]; int book_id; }; int main() { struct Book book1; struct Book *pointer; pointer = &book1; // book1 title and book_id strcpy(pointer->title, "C Programming"); pointer->book_id = 6495407; // book1 author and subject strcpy(pointer->author, "Nuha Ali"); strcpy(pointer->subject, "C Programming Tutorial"); // Print book1 info printf("Book title : %s\n", pointer->title); printf("Book author : %s\n", pointer->author); printf("Book subject : %s\n", pointer->subject); printf("Book book_id : %d\n", pointer->book_id); return 0; }
Advantages of Using Pointers with Structures in C:
- Efficiency in Memory Use: Pointers allow you to handle large structures without making full copies, saving memory.
- Dynamic Data Structures: They are crucial in dynamic data structures like linked lists, trees, and graphs.
- Function Arguments: Passing structures as pointers to functions is more efficient than passing the whole structure.
- Flexibility: Pointers provide more control and flexibility in accessing and manipulating data in structures.
Structure using Pointer in C Language with Real-Time Examples
In C, using pointers with structures is a common practice, particularly useful for dynamic memory allocation, passing structures to functions, and creating complex data structures like linked lists or trees. Here are some examples to illustrate the use of structures with pointers:
Example: Accessing Structure Members via Pointer
This example demonstrates how to access the members of a structure using a pointer to that structure.
#include <stdio.h> struct Point { int x; int y; }; int main() { struct Point point1 = {10, 20}; struct Point *pointPtr = &point1; // Accessing structure members printf("Point x: %d\n", pointPtr->x); printf("Point y: %d\n", pointPtr->y); return 0; }
In this example, pointPtr is a pointer to a struct Point. We use the arrow operator (->) to access the x and y of point1.
Example: Dynamic Memory Allocation for Structures
This example shows how to dynamically allocate memory for a structure and then access its members.
#include <stdio.h> #include <stdlib.h> struct Employee { int id; float salary; }; int main() { struct Employee *emp = malloc(sizeof(struct Employee)); if (emp == NULL) { // Handle memory allocation failure return 1; } emp->id = 123; emp->salary = 45000.50; printf("Employee ID: %d\n", emp->id); printf("Employee Salary: %.2f\n", emp->salary); free(emp); return 0; }
In this example, emp is a pointer to a dynamically allocated struct Employee, and memory is allocated using malloc.
Example: Passing Structure Pointer to a Function
Passing a pointer to a structure to a function is useful, especially for large structures.
#include <stdio.h> struct Rectangle { int length; int width; }; // Function to calculate the area of a rectangle int calculateArea(struct Rectangle *r) { return r->length * r->width; } int main() { struct Rectangle rect = {10, 15}; printf("Area of Rectangle: %d\n", calculateArea(&rect)); return 0; }
The function calculateArea receives a pointer to the struct Rectangle, which is more efficient than passing a whole structure.
Example: Pointers within Structures
Sometimes, a structure might have pointers as its members.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Student { char *name; int age; }; int main() { struct Student student1; student1.age = 20; student1.name = malloc(50 * sizeof(char)); // Allocating memory for the name strcpy(student1.name, "Alice"); printf("Name: %s, Age: %d\n", student1.name, student1.age); free(student1.name); // Remember to free the allocated memory return 0; }
In this example, the name is a pointer within the struct Student, and memory for the name is dynamically allocated.
When to Use Pointers with Structures in C?
Using pointers with structures in C is a common practice with various applications. Deciding when to use pointers instead of regular structure variables depends on several factors. Here are some scenarios where pointers to structures are particularly useful:
- Dynamic Memory Allocation: When the size of the structure is large or not known at compile time, pointers with dynamic memory allocation (malloc, calloc) can be used. This is essential in creating flexible and memory-efficient programs. This approach is also vital in creating dynamic data structures like linked lists, trees, or graphs.
- Passing Structures to Functions: Passing a pointer to a structure to a function is more efficient than passing the entire structure, especially for large structures. This avoids the overhead of copying the entire structure, which can be costly regarding memory and processing time. Pointers allow functions to modify the actual structure, not just a copy, which is essential for functions that need to alter the data within a structure.
- Arrays of Structures: Using pointers is more efficient when dealing with arrays of structures, especially if the arrays are large. It reduces the memory footprint and improves the performance of operations on the array elements.
- Complex Nested Structures: Pointers can simplify access and manipulation in cases of complex nested structures. They allow easier and more readable access to deep nesting levels within structures.
- Shared Data Among Functions or Modules: When multiple functions or modules need to access and possibly modify the same instance of a structure, pointers are used to share the data without creating multiple copies.
- Implementation of Data Abstraction and Encapsulation: Pointers to structures are often used in the implementation of abstract data types (ADTs) in C. They provide a level of data abstraction and encapsulation, which is crucial in large-scale software development.
Combining structures with pointers enhances the flexibility and efficiency of C programs. It allows for dynamic memory management, efficient data processing, and the implementation of advanced data structures. When using pointers in structures, it’s important to manage memory properly to avoid leaks and other memory-related errors.
In the next article, I will discuss Structure Real-Time Examples in C Language. In this article, I explain Structure using Pointer in C Language with Examples. I hope you enjoy this Structure using Pointer in C Language with Examples article. I would like to have your feedback. Please post feedback, questions, or comments about this article.