C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Pointers
  5. Pointers and Structures

Pointers and Structures

In C, structures (struct) are used to group different data types together under one name.

  • You can use pointers to structures to efficiently access or modify structure members.
  • Pointer to structure stores the address of the structure variable.
  • To access members via a structure pointer, use the -> operator instead of the dot (.) operator.

Why use Pointers with Structures?

  • Passing large structures to functions is expensive (copies all data), so passing a pointer is more efficient.
  • Dynamically allocate memory for structures using pointers.
  • To manipulate the structure directly from memory address.

Syntax:

struct StructureName {
    data_type member1;
    data_type member2;
    // ... other members
};

struct StructureName *ptr;   // pointer to a structure
  • Access member through pointer: ptr->member
  • Access member through structure variable: structVar.member

Example:

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p1 = {10, 20};
    struct Point *ptr;

    ptr = &p1;  // pointer points to structure p1

    // Access structure members using pointer
    printf("x = %d, y = %d\n", ptr->x, ptr->y);

    // Modify members using pointer
    ptr->x = 30;
    ptr->y = 40;

    printf("Modified x = %d, Modified y = %d\n", p1.x, p1.y);

    return 0;
}

How can we help?

Discussion 0

Join the Conversation

Your email address will not be published. Required fields are marked *