top

Search

C Tutorial

.

UpGrad

C Tutorial

Structures in C

What Is a Structure?

Structures in C are user-defined data types that compile two or more alike or diverse data structures or data types together in a single variant. You can create a structure variable with the help of the keyword struct and the structure tag name. Using the data type formed via structure in C, you can define a pointer, include structure as a return type in a function, or pass structure as a function argument.

For example, you can create a structure for an employee. You can use a character array to store the title, an integer to store the employee id, etc.

Why Use Structure?

Using structures in C tackles the limitation of arrays. In C, arrays are restrained to store variables of identical data types. By creating a structure, you can declare multiple variables of various data types. C treats these data types as a single entity.

For example, the following program helps you to store some data of an employee like a name and employeeid. We use char data type to store the name of the employee and int data type to store the employeeid.

From the above structure in C example, we can infer that it is easy to store data of a single employee but it's difficult to create variables for 100 or more employees. To deal with this issue, you can create a structure in C that stores or binds various data types together.

char Name[100];  // defines a character array to store the name of each employee
int employeeid;      // defines int variable to store employee id number

Where to use the Structure data type?

The structure data type is widely used in scenarios where you want to group associated variables to denote a single concept or entity. It is useful to signify real-world entities like a book, car, person, etc.

It is useful to denote records in a database or read data from a file. Each structure will relate to a single record. The corresponding variables would signify the various fields of the record.

Creating a Structure

If you want to form a structure in C, you must first use the keyword struct and then that structure’s tag name. The next part is the structure’s body, in which you can add the necessary data members (user-defined or primitive data types). 

Here’s the structure syntax in C 

struct structure_name
{
Data_member_type data_member_definition;
Data_member_type data_member_definition;
Data_member_type data_member_definition;
...
...
}(structure_variables);

 Here’s an example of structure in C:

struct Employee
{
char name[50];
int class;
int employee_id;
} employee1;

As seen from the mentioned syntax and example, the data type of the data_members can be char, int, array, double, or other user-defined types of data. Irrespective of the data type, the data_member_definition is simply a variable title like name, employeeid, etc. 

How to declare structure variables?

Creating a structure comprising all data members is not enough. You must create structure variables to use different properties of your devised structure in C. The following section discusses two ways to declare structure variables in C.

Approach-1:

Syntax:

struct structure_name 

{
// body of the structure
} variables;

Example:

struct Employee 

{
char name[50];
int class;
int employee_id;
} employee1; // 'employee1' is a structure variable of type, Employee.

In this example, an Employee structure is formed, and the employee1 variable is declared for it after the structure definition.

Approach-2:

After creating a structure within C, you can create a user-defined data type. It can be seen as the primitive data type when declaring a variable for the structure.

Syntax:

struct Employee
{
char name[50];
int class;
int employee_id;
};
 int main()
{
//struct structure_name variable_name;
 
struct Employee e; // here e is the variable of type Employee
return 0;
}

In the above example, the structure Employee is first created, and its variable is declared in the main() function.

Declaring Structure Variables: Which Approach is Better?

While declaring the structure variables with the structure definition, C treats them as global variables. You can use the first approach to declare global variables with the structure. If you don’t need global variables, then the next approach is suitable because it is simple to initialise or maintain variables. 

Initialising Structure Members

Initialising structure members refer to assigning values to these members as per their data types. The declaration process doesn’t assign memory for the structure. The memory is allocated to the structure variable only when you declare a variable for the particular structure. The structure members can’t be initialised during the declaration.

Defining structure in the following way gives a compile error.

Syntax:

struct Employee
{
char name[50] = {"Employee1"};// COMPILER ERROR:  cannot initialize members here
int class = 1;               // COMPILER ERROR:  cannot initialize members here
int employee_id = 2;             // COMPILER ERROR:  cannot initialize members here
};

Since we get a compile error, the question is -how to initialise the members correctly? The following section discusses three ways to initialise structure members: 

i. Using Dot '.' operator

ii. Using curly braces ‘{}’

iii. Designated initializers

i. Using Dot '.' operator

With the help of the dot (.) operator, you can access any structure member and, subsequently, initialise or allocate its value as per its data type. Here’s the syntax:

Syntax:

struct structure_name variable_name;
variable_name.member = value;

 The syntax implies that first, we create a structure variable, and then, using the dot operator, we access its member to initialise them.

ii. Using curly braces ‘{}’

If you want to initialise all the members during the declaration of the structure variable, you can use curly braces for the declaration. Here’s the syntax: 

Syntax:

struct stucture_name x1 = {value1, value2, value3, ..};

Accessing Structure Elements

The dot(.) operator allows you to directly access the structure member. This operator is used between the structure variable’s name and the structure member’s name you want to access. Here’s the syntax:

structure_variable.structure_member;

Here’s an example code to understand how to access structure elements:

#include <stdio.h>

// Defines a structure
struct Man 

{
char name[100];
int age;
};
 
int main() 

{
// Declare a variable of the structure type
struct Man man1;
 
// Access and modify structure elements
strcpy(man1.name, "James Williams");
man1.age = 29;
 
// Access and print structure elements
printf("Name is: %s\n", man1.name);
printf("Age is: %d\n", man1.age);
 
return 0;
}

 Output:

Name is: James Williams
Age is: 29

In the above example program, the structure ‘Man’ declares name and age. In the main() function, we declare and access the variables of this structure. The later section prints the values of these variables.

Understanding Designated Initialization

Designated initialization feature is introduced in the C99 standard. It lets you initialise a structure’s members through their designated indices or names. This feature allows you to easily initialise certain members of a structure without explicitly initialise all members or depending on their order.

What is an array of structures?

You can create an array of structures in C as you do with other data types. Each block works in the same manner as a single variable of the same data type. Here’s the syntax: 

struct structure_name array_name[size_of_array];

Using the above syntax, you create an array of structures with every memory block holding a single structure variable.

Let’s look at the following example program to better understand it:

#include <stdio.h>
 
// Define a structure
struct Student 

{
char name[100];
int age;
};
 
int main() {
int numofStudent;
 
// Allows the user to enter number of students
printf("Please enter the number of students: ");
scanf("%d", &numofStudent);
 
// Declare an array of structures dynamically
    struct Student *people = (struct Student *)malloc( numofStudent * sizeof(struct Student));
 
// Takes input for each student
for (int i = 0; i < numofStudent; i++) 

{
    printf("\nEnter details for Student %d:\n", i + 1);
 
    printf("Name: ");
    scanf("%s", people[i].name);
 
    printf("Age: ");
    scanf("%d", &people[i].age);
 
}
 
// Prints the details of each student
printf("\nDetails of students:\n");
for (int i = 0; i < numofStudent; i++) {
    printf("\nStudent %d:\n", i + 1);
    printf("Name: %s\n", people[i].name);
    printf("Age: %d\n", people[i].age);
}
 
// Free the dynamically allocated memory
free(people);
 
return 0;
}

Output:

Please enter the number of students: 3
Enter details for Student 1:
Name: James
Age: 14
Enter details for Student 2:
Name: Bob
Age: 13
Enter details for Student 3:
Name: John
Age: 16
Details of students:
 
Student 1:
Name: James
Age: 14
 
Student 2:
Name: Bob
Age: 13
 
Student 3:
Name: John
Age: 16

 The above code creates an array of details of students. It prompts the user to enter the details of each student and accordingly prints the output for each of them.

Nested Structures

In C, nested structures mean defining a structure within another structure. They allow you to establish a hierarchical relationship between structures.

Structure Pointer

A structure pointer refers to a pointer variable that stores the memory address of a structure. You can use it to access and dynamically operate on a structure’s members.

Structure Member Alignment

Structure member alignment in C refers to the way the members of a structure are arranged in memory. It ensures that each member is allocated at a memory address that is a multiple of its required alignment.

What is Structures as Function Arguments?

The structures in C can be passed as function arguments to let the function operate on the structure's data. You can pass structures to functions either by reference (using pointers) or by value.

Limitations of C Structures

Let’s explore a few limitations of the C structures to ensure their apt implementation while running a C program. 

  • C structures don’t support access control mechanisms or inherent data encapsulation.

  • They don’t allow you to define member functions or methods which can operate on the structure's data.

  • They don’t support derivation or inheritance.

  • They don’t support operator overloading.

Conclusion

Storing similar data of multiple entities is simplified with the use of structure in C. You can easily access a structure’s data members for further operations. Practising the use of structure in C benefits you with improved code readability and reduced code complexity.

Besides practising the tutorials, pursuing upGrad’s Master of Science in Computer Science at Liverpool John Moores University can help you elevate your career in the tech industry. The industry experts impart the content in an easy-to-understand approach to help you thoroughly grasp the concepts. Covering all the relevant and in-demand topics, upGrad paves the path to your career advancement in STEM!

Enroll now to start your journey!

FAQs

Q. What are the benefits of using structures in C programming?

Structure in C lets you define user-defined data types that can store items with varied data types. It reduces code complexity because you only need to create a structure and its array. While improving code readability, it can easily handle records containing heterogeneous data items. Thus, it increases productivity.

Q. What is the difference between functions and structures in C?

The reusable codes that perform a particular task when being called are known as functions. Structures are user-defined data types. They can have several fundamental data types called structure members sorted into a single user-defined data type. 

Q. How can you pass structure members to functions?

You can use the dot (.) operator to access each member of the structure and then pass them to the function. This approach is useful when you don’t want to pass the whole structure to the function but only pass a few of its members. 

Q. What is the difference between structure and union in C?

Structures in C are custom data types that store multiple members of varied data types within a single unit. Unions are user-defined data types that combine objects of various data types in the exact memory location. Structures allow you to initialise multiple members at once, whereas unions allow you to initialise only the first member at a time.

Leave a Reply

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