What are the Data Structures in C Programming with Examples

What are the Data Structures in C Programming with Examples

In Structures in C programming language, a user-defined datatype called structure enables us to aggregate data of various sorts. A complex data type can be built with the aid of structure to make it more meaningful. It resembles an array in certain ways, but an array only stores data of the same type. However, structure, which is more useful practically, may store data of any type.

For instance, how can I utilize arrays to solve the problem of storing student information that includes the student’s name, age, branch, permanent address, father’s name, etc., as well as string and numeric values? I need a solution that can keep data of various sorts together. Records are the framework in which data is kept.

You must test the C Language code provided in this lesson in your code editor to validate it. However, if you prefer to execute this code online, we also provide a free C Online Compiler for testing your C Language code.

Overview in Structure in C

A user-defined data type in C is called a structure. It is used to combine multiple data types—whether they are similar or dissimilar—into a single type. The struct keyword and the structure tag name are used to create a structure and a structure variable, respectively.

A data type built in C using a structure can be used in the same ways as other primitive data types in C to specify a pointer, send a structure as an argument to a function, or have a function return a structure.

Scope of Article in Structure in C

  • This article provides a fundamental understanding of structure, how to construct structure, and structure-related variables.
  • We will also see passing a pointer to a structure, a structure itself, and an array of structures as function arguments.
  • Additionally, this post covered how to align and initialize structural variables.
  • We shall also observe the structure’s limitations.

Introduction of structure in C Programming

For storing integers, characters, and decimal values, the C language has already established data types called int, char, float, and double (also known as the primitive data types).

Additionally, we have some derived data types, such arrays and strings, to group elements of the same type of data together. The issue with arrays and strings, however, is that they can only hold variables with identical data types, whereas strings can only hold characters.

What if we need to store many objects that use two different data types together in C? For instance, a student variable may contain information such as name, class, section, etc.

Therefore, if we want to save all of its data, we can construct different variables for each variable, such as a character array to save the name, an integer variable to save the class, and a character variable to save the section. However, this solution is a little disorganized. C offers us a superior, Structure, solution that is nice and orderly.

Why Use Structure in C?

Consider the situation where we need to store information about a student, such as Name, Class, and Section. There is one way to make a character array to hold the Name, an integer for the Class, and a character for the Section, as in:

char Name[50];      // character array to store name of student
int Class;          // int variable to store class of student
char Section;        // char variable to store section of student

Imagine having to create that many variables for 50 students, or even 500 or more. Storing data for a single student is simple. Therefore, in order to solve this kind of issue, we need to develop a user-defined data type that can store or link various data types together. In C, this may be accomplished with the aid of structure.

What is a Structure in C?

The structure, which links two or more data types or data structures together, is a user-defined data structure. In the same way that we can store a student’s information, we can design a structure for students that has the following data types: character arrays for name, integers for roll number, characters for section, etc.

Memory space is not used up by structures unless variables are defined for them. Depending on the type of the data member and alignment, its variables require certain memory space when defined (discussed below).

How to Create a Structure in C?

In C, the struct keyword is used before the structure’s tag name to build a structure. The appropriate data members (primitive or user-specified data types) are then added to the structure’s defined body.

How to Declare Structure Variables in C?

How can we use a student structure that we constructed to store student data that includes data members like student name, student class, and student section? Structure variables must be created in C before we can use the built structure’s properties.

Which Approach of Declaring Structure Variables Is Better?

The structure variables function as global variables if they are declared along with the structure definition (means they can be accessed in the whole program).

The ideal technique to create variables is to use the second approach because it is simple to maintain or initialize variables. If we need global variables, we can declare variables with the structure.

How to Initialize Structure Members?

Assigning values to structure members in accordance with their appropriate data types is known as initializing a structure member. However, no memory is set aside for the structure during declaration.

Only once a variable for a structure is declared is memory allotted to that variable. Therefore, giving something value without giving it memory is like offering food without a plate—not a smart idea! In essence, initializing structure members during declaration is not allowed.

Defining a Structure

You must first specify the data type of structural variables before you can construct them. The keyword struct is used to define a struct.

Syntax of structure in C Programming

struct [structure_tag]
{
    //member structure 1
    //member structure 2
    //member structure 3
    ...
}[structure_variables];

As you can see from the syntax above, we begin with the struct keyword, after which giving your structure a name is optional (though we recommend doing so), and then we have to list all of the member variables inside of curly braces. These member variables are simply standard C language variables of various types, such as int, float, array, etc.

Again, this is optional. We can define one or more structure variables after the final curly brace.

Note: A semicolon must come after the closing curly brace in the structure type declaration (;).

For example,

struct Student
{
    char emp_name[25];
    int emp_age;
    char emp_branch[10];
  
    char emp_gender;
};

This struct Student specifies a structure to house a student’s information. This structure contains 4 data fields: name, age, branch, and gender. Structure members or elements are the names given to these fields.

Each member may have a unique datatype. For example, in this instance, the name is an array of the char type, the age is an int type, etc. The structure’s name and tag both contain the word “student.”

Declaring Structure Variables in C

A structure’s variables in C can be declared either as part of the structure definition process or after the structure has been established.

Declaring a structure variable is comparable to declaring a regular variable of any other datatype. The two methods listed below can be used to declare structure variables:

Declaring Structure variables separately

struct Student
{
    char emp_name[25];
    int emp_age;
    char emp_branch[10];
  
    char emp_gender;
};
struct Student T1, T2;      //declaring variables of struct Student

Declaring Structure variables with structure definition in C

struct Student
{
    char emp_name[25];
    int emp_age;
    char emp_branch[10];
  
    char emp_gender;
} T1, T2;      //declaring variables of struct Student

Here, the Student structure’s variables T1 and T2 are used. However, this course of action is not often advised.

Accessing Structure Members

There are numerous ways to access structure members and set values to them. Without the structure, the individual elements of the structure are meaningless.

Any structure member must be linked with the structure variable using the dot. operator, also known as the period or member access operator, in order to receive a value.

Example in Accessing Structure Members in C Programming

#include<stdio.h>
#include<string.h>
struct Student
{
    char emp_name[25];
    int emp_age;
    char emp_branch[10];
    char emp_gender;
};
int main()
{
    struct Student T1;
    
  
    T1.age = 21;
    strcpy(s1.name, "romeo");
  
    printf("Name of Student 1: %s\n", T1.name);
    printf("Age of Student 1: %d\n", T1.age);
    
    return 0;
}

Output of the above example

Name of Student 1: romeo
Age of Student 1: 21

You can try to test here the example above!

Example 2: in Accessing Structure Members in C Programming

#include <stdio.h>
#include <string.h>
struct Person {
  char emp_name[50];
  int emp_citNo;
  float emp_salary;
} employee1;
int main() {
  
  strcpy(employee1.emp_name, "Juan Delacruz");
 
  employee1.emp_citNo = 1820;
  employee1. emp_salary = 50000;
 
  printf("Name: %s\n", employee1.emp_name);
  printf("Citizenship No.: %d\n", employee1.emp_citNo);
  printf("Salary: %.2f", employee1.emp_salary);
  return 0;
}

Output of the above example

Name: Juan Delacruz
Citizenship No.: 1820
Salary: 50000.00

We have generated a struct called Person in this program. Additionally, we developed a employee1 variable.

The variables specified in Person for the employee1 object have values assigned in main().

strcpy(employee1.emp_name, “Juan Delacruz”);
employee1.emp_citNo = 1820;
employee1. emp_salary = 50000;

You’ll see that we assigned the value to employee1.empname using the strcpy() function.

This is due to the fact that emp_name is a char array (C-string), and after the string has been declared, we are unable to use the assignment operator = with it.

You can try to test here the example above!

Keyword typedef in Structure in C

The typedef keyword is used to give data types an alias name. It is frequently used with structures to make variable declaration syntax simpler.

Let’s examine the following code as an illustration:

struct Distance{
  int ft;
  float inches;
};
int main() {
  struct Distance dis1, dis2;
}

To create an analogous code with a more easy syntax, we can use typedef:

typedef struct Distance {
  int ft;
  float inches;
} distances;
int main() {
  distances dis1, dis2;
}

Example of Keyword typedef in Structure in C

#include <stdio.h>
#include <string.h>
typedef struct Person {
  char empname[50];
  int empcitNo;
  float empsalary;
} person;
int main() {
 
  person emp1;
  strcpy(emp1.empname, "Romeo Nicolas");
  
  emp1.empcitNo = 1500;
  emp1.empsalary = 500000;
  
  printf("Name: %s\n", emp1.empname);
  printf("Citizenship No.: %d\n", emp1.empcitNo);
  printf("Salary: %.2f", emp1.empsalary);
  return 0;
}

Output of the above example

Name: Romeo Nicolas
Citizenship No.: 1500
Salary: 500000.00

Here, an alias person has been made using typedef and the Person structure.

typedef struct Person {
  // code
} person;

Now that we have the person alias, we can easily declare a Person variable:

// equivalent to struct Person p1
person emp1;

You can try to test here the example above!

Structure Initialization in C Program

Structure variables can also be initialized at build time, just like variables of other datatypes.

For Example:

struct Patient
{
    float emp_height;
    int emp_weight;  
    int emp_age; 
};
struct Patient pemp1 = { 180.75 , 73, 23 };    //initialization

or

struct Patient emp1;
emp1.emp_height = 180.75;     //initialization of each member separately
emp1.emp_weight = 73;
emp1.emp_age = 23;

Array of Structure in C

An array of structure variables can also be declared. And each array entry corresponds to a structural variable. struct employee emp[5] is an example.

The software below defines an emp array of size 5. The array emp’s elements are all of the Employee type.

Example of Array Structure in C

#include<stdio.h>
struct Employee
{
    char emp_name[10];
    int emp_salary;
};
struct Employee emp[5];
int x, j;
void ask()
{
    for(x = 0; x < 3; x++)
    {
        printf("\nEnter %dst Employee record:\n", x+1);
        printf("\nEmployee name:\t");
        scanf("%s", emp[x].emp_name);
        printf("\nEnter Salary:\t");
        scanf("%d", &emp[x].emp_salary);
    }
    printf("\nDisplaying Employee record:\n");
    for(x = 0; x < 3; x++)
    {
        printf("\nEmployee name is %s", emp[x].emp_name);
        printf("\nSlary is %d", emp[x].emp_salary);
    }
}
void main()
{
    ask();
}

Output of the above example

Enter 1st Employee record:
Employee name:
Enter Salary:
Enter 2st Employee record:

Employee name:
Enter Salary:
Enter 3st Employee record:

Employee name:
Enter Salary:
Displaying Employee record:

Employee name is Romeo
Slary is 5000
Employee name is Roland
Slary is 10000
Employee name is Rodrigo
Slary is 100000
Command exited with non-zero status 3

You can try to test here the example above!

Nested Structures in C

In the C language, nesting of structures is also allowed. Structures that are nested together have a different structure as a member variable.

In C programming, structures within structures are possible. For example,

struct complex {
  int image;
  float real;
};
struct number {
  struct complex comp;
  int integers;
} number1, number2;

Let’s say you wish to set the num2 variable’s image to 11. Here is how to go about it:

number2.comp.image = 11;

Example of Nested Structures in C

#include <stdio.h>
struct complex {
  int images;
  float real;
};
struct number {
  struct complex comp;
  int integer;
} number1;
int main() {
  // initialize complex variables
  number1.comp.images = 11;
  number1.comp.real = 5.25;
  // initialize number variable
  number1.integer = 6;
	
  // print struct variables
  printf("Imaginary Part: %d\n", number1.comp.images);
  printf("Real Part: %.2f\n", number1.comp.real);
  printf("Integer: %d", number1.integer);
  return 0;
}

Output of the above example

Imaginary Part: 11
Real Part: 5.25
Integer: 6

You can try to test here the example above!

Structure as Function Arguments in C

A structure can be passed as a function argument in the same way that we can pass any other variable or an array.

Example of Structure as Function Arguments in C

#include<stdio.h>
struct Student
{
    char emp_name[10];
    int emp_roll;
};
void show(struct Student st);
void main()
{
    struct Student std;
    printf("\nEnter Student record:\n");
    printf("\nStudent name:\t");
    scanf("%s", std.emp_name);
    printf("\nEnter Student rollno.:\t");
    scanf("%d", &std.emp_roll);
    show(std);
}
void show(struct Student st)
{
    printf("\nstudent name is %s", st.emp_name);
    printf("\nroll is %d", st.emp_roll);
}

Output of the above example

Enter Student record:
Student name:
Enter Student rollno.:
student name is romeo
roll is 51820

You can try to test here the example above!

Why structs in C?

Let’s say you wish to keep a person’s name, citizenship number, and income on file. To store this data, you can construct various variables like name, citNo, and salary.

What if you need to keep the personal data of multiple people? You must now construct distinct variables for each piece of data per person, such as name1, citNo1, salary1, name2, citNo2, etc.

A better strategy would be to utilize the same Person structure for every person and compile all relevant data under that name.

Summary

In conclusion, you have studied the fundamentals of a structure in C programming from this article, Structure in C Programming. You began with a brief explanation of a C structure before moving on to talk about its applications. The syntax of structures, how to declare and initialize a structure in C, and how to access a structure’s elements were the following topics you studied.

Next, you learnt about the initialization of a structure in C, an array of structures, and a pointer to a structure in the essay on structures in C programming. You briefly discussed nested structures and the constraints of a structure in C near the end of the article.

Inquiries

If you have any questions or suggestions about What are the Data Structures in C Programming with Examples, please feel free to leave a comment below.

About Next Tutorial

In the next following post, I’ll create a Unions in C and try to explain its many components in full details. I hope you enjoy this post on What are the Data Structures in C Programming with Examples, in which I attempt to illustrate the language’s core grammar.

Leave a Comment