Structure Pointer in C

Structure Pointer in C

Structure pointer in C is where a pointer variable can point to the address of a structure variable. Here is how we can declare a pointer to a structure variable. We can also have a pointer to a single structure variable, but it is mostly used when we are dealing with an array of structure variables.

 

Example

struct emp
{
   int value;
};

// Driver Code
int main()
{
    struct emp s;
    struct emp *ptr = &s;
    return 0;
}

 

Declare a Structure Pointer

struct structure_name *ptr;

 

Initialization of the Structure Pointer

ptr = &structure_variable;

 

Accessing members using Pointer

There are two ways of accessing members of structure using pointer:

  1. Using indirection (*) operator and dot (.) operator.
  2. Using arrow (->) operator or membership operator.

 

To access members of structure using the structure variable, we used the dot . operator. But when we have a pointer of structure type, we use arrow -> to access structure members.

 

Program

#include <stdio.h>

struct my_structure {
    char name[20];
    int number;
    int rank;
};

int main()
{
    struct my_structure variable = {"StudyTonight", 35, 1};

    struct my_structure *ptr;
    ptr = &variable;

    printf("NAME: %s\n", ptr->name);
    printf("NUMBER: %d\n", ptr->number);
    printf("RANK: %d", ptr->rank);

    return 0;
}

 

Output

NAME: ABC
NUMBER: 40
RANK: 1

 

Also, read the Function Pointer in C

Share this post

Leave a Reply

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