C Structs and Pointers

1. Pointer to a Structure

  • 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 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).

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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