C Structs and Pointers

C Tutorial

1. C Structs and Pointers

  • You can create a pointer that points to a structure variable.

  • Useful when passing structures to functions or for dynamic memory allocation.

Syntax:


  • Access members using arrow -> operator instead of dot ..


2. Example: Basic Structure Pointer


 

Output:

ID: 101
Name: Alice
Marks: 95.50

ptr->member is equivalent to (*ptr).member.


3. Using Pointer with Array of Structures


Output:

ID: 101, Name: Alice
ID: 102, Name: Bob

4. Passing Structure Pointer to Function

  • Passing a structure pointer to a function avoids copying the whole structure.


 

Output:

ID: 101, Name: Alice

5. Dynamic Memory Allocation with Struct Pointer


 

  • malloc allocates memory dynamically for a structure.

  • Always use free() to release memory.


6. Key Points About C Structs and Pointers

  1. Use struct StructName *ptr to create a structure pointer.

  2. Access members using arrow -> (ptr->member).

  3. Arrays of structures can be accessed using pointer arithmetic ((ptr+i)->member).

  4. Passing structure pointers to functions saves memory.

  5. Combine with malloc for dynamic memory allocation.

  6. (*ptr).member is equivalent to ptr->member (less convenient).

You may also like...