What is a C struct?

C struct, short for C Structure, is an user-defined data type available in C. It allows a user to combine data items of possibly different data types under a single name.

C structs are different from arrays because arrays hold data of similar data-types only. C struct, on the other hand, can store data of multiple data-types.

Each element in the structure is called a member.

Syntax

A structure is defined by using the struct keyword. A structure is a possible collection of primary data types and other structures as well.

  • The structure_name holds the name we want to give to our structure.
  • data_type variable is the C variables of different data types like int, char, float etc.
struct structure_name
{
//data_type variable 1
//data_type variable 2
//data_type variable 3
...
};

Defining a structure

The code below initializes a structure Employee having three member variables:

  • name: An array of char type.
  • age: A variable of int type.
  • salary: A variable of float type.
struct Employee
{
char name[50];
int age;
float salary;
};
svg viewer

Initializing a structure

Structures can be assigned values when they are initialized.

Before initialization:

struct Employee
{
char name[50];
int age;
float salary;
};
int main() {
struct Employee e1 = {"John", 32, 4200};
//accessing the values in the variable
printf("Name: %s\n", e1.name);
printf("Age : %d\n", e1.age);
printf("Salary : %f\n", e1.salary);
}

After initialization:

struct Employee
{
char name[50];
int age;
float salary;
};
int main() {
struct Employee e1;
strcpy(e1.name, "John");
e1.age = 32;
e1.salary = 4200;
//accessing the values in the variable
printf("Name: %s\n", e1.name);
printf("Age : %d\n", e1.age);
printf("Salary : %f\n", e1.salary);
}

Accessing a Structure

The values in a structure variable can be accessed in the following manner:

struct Employee
{
char name[50];
int age;
float salary;
};
int main() {
struct Employee e1 = {"John", 32, 4200};
//accessing the values in the variable
printf("Name: %s\n", e1.name);
printf("Age : %d\n", e1.age);
printf("Salary : %f\n", e1.salary);
}

Copyright ©2024 Educative, Inc. All rights reserved