Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Pointer to Structure in C Language

Introduction

In C programming, structures are used to group different data types together. A pointer to a structure is a pointer that points to the memory location of a structure. This can be particularly useful when dealing with arrays of structures or passing structures to functions.

Defining a Structure

Before we can use pointers to structures, we need to define a structure. Here is an example of a simple structure:

struct Person {
    char name[50];
    int age;
    float salary;
};

Declaring a Pointer to a Structure

Once we have a structure, we can declare a pointer to it. Here’s how we can declare a pointer to the Person structure:

struct Person *personPtr;

Assigning Address to a Structure Pointer

We can assign the address of a structure variable to the structure pointer. Here's an example:

struct Person person1;
struct Person *personPtr;
personPtr = &person1;

Accessing Structure Members Using Pointer

There are two ways to access the members of a structure using a pointer: the -> operator and the dereference operator *.

Using the Arrow Operator (->)

The arrow operator allows us to directly access the members of the structure:

personPtr->age = 30;
strcpy(personPtr->name, "John Doe");
personPtr->salary = 50000.0f;

Using the Dereference Operator (*)

We can also use the dereference operator to access the structure members:

(*personPtr).age = 30;
strcpy((*personPtr).name, "John Doe");
(*personPtr).salary = 50000.0f;

Complete Example

Here is a complete example that demonstrates the use of pointers to structures:

#include <stdio.h>
#include <string.h>

struct Person {
    char name[50];
    int age;
    float salary;
};

int main() {
    struct Person person1;
    struct Person *personPtr;

    personPtr = &person1;

    // Using arrow operator to assign values
    personPtr->age = 30;
    strcpy(personPtr->name, "John Doe");
    personPtr->salary = 50000.0f;

    // Printing values
    printf("Name: %s\n", personPtr->name);
    printf("Age: %d\n", personPtr->age);
    printf("Salary: %.2f\n", personPtr->salary);

    return 0;
}

Output:

Name: John Doe
Age: 30
Salary: 50000.00

Conclusion

Pointers to structures are a powerful feature in C that allows for efficient manipulation and access of structure data. Understanding how to use these pointers is essential for working with complex data types and structures in C programming.