Open In App

C Structures

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type. Additionally, the values of a structure are stored in contiguous memory locations.

C Structures

C Structure Declaration

We have to declare structure in C before using it in our program. In structure declaration, we specify its member variables along with their datatype. We can use the struct keyword to declare the structure in C using the following syntax:

Syntax

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};

The above syntax is also called a structure template or structure prototype and no memory is allocated to the structure in the declaration.

C Structure Definition

To use structure in our program, we have to define its instance. We can do that by creating variables of the structure type. We can define structure variables using two methods:

1. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

// structure declared beforehand
struct structure_name variable1, variable2, .......;

Access Structure Members

We can access structure members by using the ( . ) dot operator.

Syntax

structure_name.member1;
strcuture_name.member2;

In the case where we have a pointer to the structure, we can also use the arrow operator to access the members.

Initialize Structure Members

Structure members cannot be initialized with the declaration. For example, the following C program fails in the compilation.

struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

The reason for the above error is simple. When a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.

Default Initialization

By default, structure members are not automatically initialized to 0 or NULL. Uninitialized structure members will contain garbage values. However, when a structure variable is declared with an initializer, all members not explicitly initialized are zero-initialized.

struct Point
{
int x;
int y;
};

struct Point p = {0}; // Both x and y are initialized to 0

We can initialize structure members in 3 ways which are as follows:

  1. Using Assignment Operator.
  2. Using Initializer List.
  3. Using Designated Initializer List.

1. Initialization using Assignment Operator

struct structure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.

2. Initialization using Initializer List

struct structure_name str = { value1, value2, value3 };

In this type of initialization, the values are assigned in sequential order as they are declared in the structure template.

3. Initialization using Designated Initializer List

Designated Initialization allows structure members to be initialized in any order. This feature has been added in the C99 standard.

struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };

The Designated Initialization is only supported in C but not in C++.

Example of Structure in C

The following C program shows how to use structures

C
// C program to illustrate the use of structures
#include <stdio.h>

// declaring structure with name str1
struct str1 {
    int i;
    char c;
    float f;
    char s[30];
};

// declaring structure with name str2
struct str2 {
    int ii;
    char cc;
    float ff;
} var; // variable declaration with structure template

// Driver code
int main()
{
    // variable declaration after structure template
    // initialization with initializer list and designated
    //    initializer list
    struct str1 var1 = { 1, 'A', 1.00, "GeeksforGeeks" },
                var2;
    struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };

    // copying structure using assignment operator
    var2 = var1;

    printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",
           var1.i, var1.c, var1.f, var1.s);
    printf("Struct 2:\n\ti = %d, c = %c, f = %f, s = %s\n",
           var2.i, var2.c, var2.f, var2.s);
    printf("Struct 3\n\ti = %d, c = %c, f = %f\n", var3.ii,
           var3.cc, var3.ff);

    return 0;
}

Output
Struct 1:
    i = 1, c = A, f = 1.000000, s = GeeksforGeeks
Struct 2:
    i = 1, c = A, f = 1.000000, s = GeeksforGeeks
Struct 3
    i = 5, c = a, f = 5.000000

typedef for Structures

The typedef keyword is used to define an alias for the already existing datatype. In structures, we have to use the struct keyword along with the structure name to define the variables. Sometimes, this increases the length and complexity of the code. We can use the typedef to define some new shorter name for the structure.

Example

C
// C Program to illustrate the use of typedef with
// structures
#include <stdio.h>

// defining structure
typedef struct {
    int a;
} str1;

// another way of using typedef with structures
typedef struct {
    int x;
} str2;

int main()
{
    // creating structure variables using new names
    str1 var1 = { 20 };
    str2 var2 = { 314 };

    printf("var1.a = %d\n", var1.a);
    printf("var2.x = %d\n", var2.x);

    return 0;
}

Output
var1.a = 20
var2.x = 314

Nested Structures

C language allows us to insert one structure into another as a member. This process is called nesting and such structures are called nested structures. There are two ways in which we can nest one structure into another:

1. Embedded Structure Nesting

In this method, the structure being nested is also declared inside the parent structure.

Example

struct parent {
int member1;
struct member_str member2 {
int member_str1;
char member_str2;
...
}
...
}

2. Separate Structure Nesting

In this method, two structures are declared separately and then the member structure is nested inside the parent structure.

Example

struct member_str {
int member_str1;
char member_str2;
...
}

struct parent {
int member1;
struct member_str member2;
...
}

One thing to note here is that the declaration of the structure should always be present before its definition as a structure member. For example, the declaration below is invalid as the struct mem is not defined when it is declared inside the parent structure.

struct parent {
struct mem a;
};

struct mem {
int var;
};

Accessing Nested Members

We can access nested Members by using the same ( . ) dot operator two times as shown:

str_parent.str_child.member;

Example of Structure Nesting

C
// C Program to illustrate structure nesting along with
// forward declaration
#include <stdio.h>

// child structure declaration
struct child {
    int x;
    char c;
};

// parent structure declaration
struct parent {
    int a;
    struct child b;
};

// driver code
int main()
{
    struct parent var1 = { 25, 195, 'A' };

    // accessing and printing nested members
    printf("var1.a = %d\n", var1.a);
    printf("var1.b.x = %d\n", var1.b.x);
    printf("var1.b.c = %c", var1.b.c);

    return 0;
}

Output
var1.a = 25
var1.b.x = 195
var1.b.c = A

Structure Pointer in C

We can define a pointer that points to the structure like any other variable. Such pointers are generally called Structure Pointers. We can access the members of the structure pointed by the structure pointer using the ( -> ) arrow operator.

Example of Structure Pointer

C
// C program to illustrate the structure pointer
#include <stdio.h>

// structure declaration
struct Point {
    int x, y;
};

int main()
{
    struct Point str = { 1, 2 };

    // p2 is a pointer to structure p1
    struct Point* ptr = &str;

    // Accessing structure members using structure pointer
    printf("%d %d", ptr->x, ptr->y);

    return 0;
}

Output
1 2

Self-Referential Structures

The self-referential structures in C are those structures that contain references to the same type as themselves i.e. they contain a member of the type pointer pointing to the same structure type.

Example of Self-Referential Structures

struct structure_name {
data_type member1;
data_type member2;
struct structure_name* str;
}
C
// C program to illustrate the self referential structures
#include <stdio.h>

// structure template
typedef struct str {
    int mem1;
    int mem2;
    struct str* next;
}str;

// driver code
int main()
{
    str var1 = { 1, 2, NULL };
    str var2 = { 10, 20, NULL };

    // assigning the address of var2 to var1.next
    var1.next = &var2;

    // pointer to var1
    str *ptr1 = &var1;

    // accessing var2 members using var1
    printf("var2.mem1: %d\nvar2.mem2: %d", ptr1->next->mem1,
           ptr1->next->mem2);

    return 0;
}

Output
var2.mem1: 10
var2.mem2: 20

Such kinds of structures are used in different data structures such as to define the nodes of linked lists, trees, etc.

C Structure Padding and Packing

Technically, the size of the structure in C should be the sum of the sizes of its members. But it may not be true for most cases. The reason for this is Structure Padding.

Structure padding is the concept of adding multiple empty bytes in the structure to naturally align the data members in the memory. It is done to minimize the CPU read cycles to retrieve different data members in the structure.

There are some situations where we need to pack the structure tightly by removing the empty bytes. In such cases, we use Structure Packing. C language provides two ways for structure packing:

  1. Using #pragma pack(1)
  2. Using __attribute((packed))__

Example of Structure Padding and Packing

C
// C program to illustrate structure padding and packing
#include <stdio.h>

// structure with padding
struct str1 {
    char c;
    int i;
};

struct str2 {
    char c;
    int i;
} __attribute((packed)) __; // using structure packing

// driver code
int main()
{

    printf("Size of str1: %d\n", sizeof(struct str1));
    printf("Size of str2: %d\n", sizeof(struct str2));
    return 0;
}

Output
Size of str1: 8
Size of str2: 5

As we can see, the size of the structure is varied when structure packing is performed.

To know more about structure padding and packing, refer to this article – Structure Member Alignment, Padding and Data Packing.

Bit Fields

Bit Fields are used to specify the length of the structure members in bits. When we know the maximum length of the member, we can use bit fields to specify the size and reduce memory consumption.

Syntax of Bit Fields

struct structure_name {
data_type member_name: width_of_bit-field;
};

 Example of Bit Fields

C
// C Program to illustrate bit fields in structures
#include <stdio.h>

// declaring structure for reference
struct str1 {
    int a;
    char c;
};

// structure with bit fields
struct str2 {
    int a : 24; // size of 'a' is 3 bytes = 24 bits
    char c;
};

// driver code
int main()
{
    printf("Size of Str1: %d\nSize of Str2: %d",
           sizeof(struct str1), sizeof(struct str2));
    return 0;
}

Output
Size of Str1: 8
Size of Str2: 4

As we can see, the size of the structure is reduced when using the bit field to define the max size of the member ‘a’.

Uses of Structure in C

C structures are used for the following:

  1. The structure can be used to define the custom data types that can be used to create some complex data types such as dates, time, complex numbers, etc. which are not present in the language.
  2. It can also be used in data organization where a large amount of data can be stored in different fields.
  3. Structures are used to create data structures such as trees, linked lists, etc.
  4. They can also be used for returning multiple values from a function.

Limitations of C Structures

In C language, structures provide a method for packing together data of different types. A Structure is a helpful tool to handle a group of logically related data items. However, C structures also have some limitations.

  • Higher Memory Consumption: It is due to structure padding.
  • No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the structure.
  • Functions inside Structure: C structures do not permit functions inside the structure so we cannot provide the associated functions.
  • Static Members: C Structure cannot have static members inside its body.
  • Construction creation in Structure: Structures in C cannot have a constructor inside Structures.

Related Articles



Previous Article
Next Article

Similar Reads

Difference Between C Structures and C++ Structures
Let's discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. Differences Between the C and C++ StructuresC Structures C++ Structures Only data members are allowed, it cannot have member functions.Can hold both: member functions and data members.Cannot have static members.Can have
6 min read
Structures in C++
We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.Unlike Arrays, Structures in C++ are user defined data types which are used to store group of items of non
5 min read
Slack Bytes in Structures : Explained with Example
Structures: Structures are used to store the data belonging to different data types under the same variable name. An example of a structure is as shown below: struct STUDENT { char[10] name; int id; }; The memory space for the above structure would be allocated as shown below: Here we see that there is no empty spaces in between the members of the
3 min read
What are the C programming concepts used as Data Structures
Data Types Data-type in simple terms gives us information about the type of data. Example, integer, character, etc. Data-types in C language are declarations for the variables. Data-types are classified as: Primitive or Built-in data types Some of the examples of primitive data types are as follows Variable named ch refers to the memory address 100
10 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a Structure A structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain element
5 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Top 50 C Coding Interview Questions and Answers (2024)
C is the most popular programming language developed by Dennis Ritchie at the Bell Laboratories in 1972 to develop the UNIX operating systems. It is a general-purpose and procedural programming language. It is faster than the languages like Java and Python. C is the most used language in top companies such as LinkedIn, Microsoft, Opera, Meta, and N
15+ min read
Top 25 C Projects with Source Codes for 2024
If you're looking for project ideas to boost your C Programming skills, you're in the right spot. Programming is about problem-solving and adapting to ever-changing technology. Start with C, the foundation of many modern languages, to refine your programming abilities. Despite being introduced 50 years ago, C remains a top choice for beginners due
14 min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library &lt;stdio.h&gt; and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatted_string", arguments_list);Parametersformatted_st
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
C Program to Add Two Integers
Write a C program for the addition of two integers. Adding two integers involves summing their values to produce a single integer result. For example, the addition of two numbers 10 and 5 results in the number 15. Examples Input: a = 5, b = 3 Output: 8 Explanation: The sum of 5 and 3 is 8. Input: a = -2, b = 7 Output: 5 Explanation: The sum of -2 a
6 min read
Prime Number Program in C
A prime number is a natural number greater than 1 and is completely divisible only by 1 and itself. In this article, we will learn how to check whether the given number is a prime number or not in C. Examples Input: N = 29Output: YesExplanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number. Input: N = 15Output: NoExpla
3 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Converting Number to String in C++
In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let's look at some methods to convert an integer or a number to a s
4 min read
std::sort() in C++ STL
We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access) It generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. The
6 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read