HOME HTML EDITOR C JAVA PHP

C Structure Pointers: Efficient Data Access

When you work with large structures containing arrays or many members, copying them during function calls consumes time and stack memory. A Structure Pointer allows you to refer to the original data directly via its memory address.

1. Declaring and Initializing Structure Pointers

To declare a pointer to a structure, use the struct keyword followed by the tag name and an asterisk (*).

struct Person {
    char name[30];
    int age;
};

int main() {
    struct Person p1 = {"John", 30};
    struct Person *ptr; // Declaration
    ptr = &p1; // Pointer now points to p1
    return 0;
}

2. The Arrow Operator (->)

In C, you cannot use the dot operator (.) directly with a pointer. While you could write (*ptr).age, it is clunky. Instead, C provides the **Arrow Operator** (->) as a shorthand for accessing members via a pointer.

// These two are identical, but the second is standard:
(*ptr).age = 31;
ptr->age = 31; // Professional way

3. Passing Structs to Functions (By Reference)

By passing a pointer to a function, any changes made to the structure members inside that function will permanently modify the original structure.

void celebrateBirthday(struct Person *p) {
    p->age += 1; // Direct modification
}

int main() {
    struct Person p1 = {"John", 30};
    celebrateBirthday(&p1);
    printf("New age: %d", p1.age); // Output: 31
}

4. Dynamic Memory Allocation for Structs

Structure pointers are essential when you don't know how many structures you need until the program is running. You can use malloc() to allocate space for a struct on the **Heap**.

struct Person *ptr = (struct Person*) malloc(sizeof(struct Person));
if (ptr != NULL) {
    ptr->age = 25;
    free(ptr); // Always free heap memory!
}

5. Summary Table

Feature Structure Variable Structure Pointer
Operator Dot operator (.) Arrow operator (->)
Memory Use Stores actual data values Stores a 4 or 8-byte address
Efficiency Slow for large structures Highly efficient
Pro Tip: When using the arrow operator with nested structures, only use -> for the level that is a pointer. For example, if ptr is a pointer to a struct that contains a normal struct dob, use: ptr->dob.year.