Skip to main content

Accessing Structure Members in C

Accessing Structure Members

In C, you can access structure members using the dot (.) operator.

Here's the syntax:

structure_variable.member_name

The structure_variable is the variable of the structure type, and member_name is the name of the member variable within the structure.

Example

#include <stdio.h>

struct person
{
char name[50];
int age;
float height;
};

int main()
{
struct person john; // declare a variable of type person

// assign values to the members of the john structure
strcpy(john.name, "John");
john.age = 25;
john.height = 6.0;

// access the members of the john structure and print them out
printf("Name: %s\n", john.name);
printf("Age: %d\n", john.age);
printf("Height: %f\n", john.height);

return 0;
}
Output:

Explanation

  • We declare a variable called john of type person
  • Then we assign values to its name, age, and height members using the dot operator.
  • We then access these members using the dot operator again and print out their values using printf().

Output:

Name: John
Age: 25
Height: 6.000000

Other ways of Accessing Structure Members

Apart from the dot (.) operator, there are other ways of accessing structure members as well.

Using the arrow (->) operator

The arrow operator is used to access a member variable of a structure through a pointer to the structure.

For example:

struct person {
char name[50];
int age;
float height;
};

struct person *p;
p = malloc(sizeof(struct person));
p->age = 30; // using arrow operator to access member 'age'

Using an array of structures

You can create an array of structures and access its members using the array index notation.

For example:

struct person {
char name[50];
int age;
float height;
};

struct person people[3];
people[0].age = 30; // using array index notation to access member
//'age' of the first structure in the array

Using a structure pointer

struct person {
char name[50];
int age;
float height;
};

struct person *p;
p = malloc(sizeof(struct person));
p->age = 30; // using arrow operator to access member 'age'
//through a pointer to the structure