Codeforwin

How to declare, initialize and access structures in C language

  • Declare structure
  • Initialize structure
  • Example program

Write a C program to declare, initialize and access structures. In this post I will explain how to declare, initialize and access structures in C language. Different ways to initialize a structure variable and how to access structure members.

Required knowledge

Basic C programming , Structures

Declare, initialize and access structures in C programming language

What is structure in C language?

Structure is a user defined data type . It is a collection of different types combined together to create a new type.

How to declare a structure?

We use struct keyword to declare a structure.

Let us declare a student structure containing three fields i.e. name , roll and marks .

How to initialize a structure variable?

C language supports multiple ways to initialize a structure variable. You can use any of the initialization method to initialize your structure.

  • Initialize using dot operator

Value initialized structure variable

Variant of value initialized structure variable, initialize structure using dot operator.

In C, we initialize or access a structure variable either through dot . or arrow -> operator . This is the most easiest way to initialize or access a structure.

The above method is easy and straightforward to initialize a structure variable. However, C language also supports value initialization for structure variable. Means, you can initialize a structure to some default value during its variable declaration.

Note: The values for the value initialized structure should match the order in which structure members are declared.

Invalid initialization:

The above code will throw compilation error . Since the order of member type in structure is character array , integer finally float. But, we aren’t initializing the structure variable in the same order.

The above approach may suit all needs. In addition, C language supports flexibility to initialize structure members in any order. I know this sounds bit confusing. As, just now I said C will throw error if you try to initialize members in different order of declaration.

This approach is an extension of above. Here, you can specify member name along with the value.

Structure default initialization

Default initialization of a variable considered as good programming practice. However, C doesn’t support any programming construct for default structure initialization. You manually need to initialize all fields to 0 or NULL .

Initializing all fields to NULL is bit cumbersome process. Let’s do a small hack to initialize structure members to default value, on every structure variable declaration.

Program to declare, initialize and access structure

Happy coding 😉

  • How to Initialize a Struct in C

Use Designated Initializers to Initialize a Struct in C

Use compound literals to initialize a struct in c, use explicit assignments to initialize a struct in c, use constructors (in c99 and later) to initialize a struct in c.

How to Initialize a Struct in C

Structs in C provide a powerful mechanism for grouping variables of diverse data types under a unified name. Properly initializing a struct is crucial for ensuring the correct functioning of your programs.

In this article, we’ll explore various methods to initialize a struct in C, each offering its advantages.

In C programming, structs serve as a pivotal tool for grouping variables of diverse data types under a unified name. When it comes to initializing a struct, one particularly versatile technique is the use of designated initializers.

This method allows for explicit specification of which members of the struct to initialize, offering clarity and flexibility in code organization.

The syntax for designated initializers involves specifying the member name followed by an equal sign and the value to assign. The general form looks like this:

This syntax allows initializing specific members of the struct while leaving others uninitialized, fostering flexibility in struct initialization.

Let’s dive into an example featuring a Person struct, representing an individual’s first name, last name, age, and a boolean indicating their vitality. Designated initializers will be employed to create an instance of this struct.

In this code snippet, we include necessary header files ( stdbool.h , stdio.h , stdlib.h , string.h ) and define a Person struct using typedef . The struct encapsulates members for the first name ( firstname ), last name ( lastname ), age, and a boolean indicating whether the person is alive ( alive ).

In the main function, we create an instance of the Person struct named me . Using designated initializers, we initialize each member of the struct with specific values.

The first name is set to John , the last name to McCarthy , the age to 24 , and the alive status to true .

The subsequent printf statement displays the information stored in the me struct. It prints the first name, last name, and age using the %s and %d format specifiers, respectively.

The last part of the output depends on the boolean value of the alive member. If alive is true , Yes is printed; otherwise, No is printed.

Finally, the program exits with EXIT_SUCCESS , indicating successful execution.

Another versatile technique to initialize a struct is using compound literals. This method allows for the creation of temporary instances of a struct with specific initial values.

The syntax for compound literals involves enclosing a list of values within parentheses and casting them to the desired struct type. The general form looks like this:

This syntax allows for the creation of an unnamed temporary instance of the struct with the specified initial values.

Let’s delve into a practical example using the Person struct:

In this example, we have a Person struct representing an individual’s first name, last name, age, and alive status. The main function initializes an instance of this struct named me using a compound literal.

The compound literal (Person){.firstname = "John\0", .lastname = "McCarthy\0", .age = 24, .alive = 1} creates a temporary instance of the Person struct with each member explicitly initialized.

This method combines clarity and conciseness, eliminating the need for a separate declaration and assignment step.

The subsequent printf statement displays the information stored in the me struct, presenting the first name, last name, age, and alive status. The output, in this case, would be:

Using compound literals in this manner enhances the readability of the code, making it clear and expressive. This approach is particularly advantageous when immediate struct initialization is preferred, providing a streamlined and elegant solution for struct initialization in C.

When initializing struct members in C, an alternative method involves declaring a variable and assigning each member with its corresponding value individually. This approach is characterized by explicit assignments, making it clear and straightforward.

It’s worth noting that when dealing with char arrays, assigning them directly with strings isn’t allowed in C. Instead, explicit copying using functions like memcpy or memmove is necessary (refer to the manual for more details).

Additionally, care should be taken to ensure that the length of the array is not less than the string being stored.

Here’s an illustrative example using a Person struct:

As we can see in this example, each member of the me2 instance is assigned a value individually. Here, the use of memcpy ensures the proper copying of string values into char arrays, respecting the necessary length constraints.

The subsequent printf statement remains unchanged, displaying the information stored in the me2 struct. The output, as before, will be:

While this approach is valid, it often involves more lines of code and can be less concise compared to using compound literals, as demonstrated in the previous section.

Compound literals provide a more streamlined and expressive way to initialize structs in C, especially when dealing with immediate initialization or temporary instances.

The concept of constructors, while not native, like in some other languages, can be emulated to achieve struct initialization.

C99 and later versions allow for a more expressive and organized approach by enabling the use of designated initializers within functions. This technique can be likened to a constructor, allowing for structured and customizable initialization of structs.

The syntax for creating a constructor-like function involves defining a function that returns an instance of the struct with designated initializers.

Here’s an example using a Person struct:

In this example, we define a Person struct with members for the first name, last name, age, and alive status. Here, the createPerson function serves as a constructor-like function, initializing and configuring a Person struct with specific values.

The function uses strncpy to copy the first and last names into the struct’s firstname and lastname members, respectively. It also ensures null-termination of the strings to prevent potential buffer overflows.

The age and alive members are then set according to the provided arguments.

In the main function, the createPerson function is used to initialize a Person struct named me . The subsequent printf statement displays the information stored in the me struct, showcasing the first name, last name, age, and alive status.

This constructor-like approach offers a structured and modular way to initialize structs in C, providing a clear and organized solution for customizable struct initialization.

Initializing structs in C involves a range of techniques, each catering to different preferences and scenarios.

Designated initializers offer clarity and flexibility, whereas compound literals provide immediate initialization. Explicit assignments ensure straightforward initialization and constructors (in C99 and later) allow for a structured approach.

Choose the method that aligns with your coding style and the specific requirements of your program. Whether you prioritize clarity, conciseness, or modularity, understanding these initialization techniques will empower you to write more efficient and maintainable C code.

Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article - C Struct

  • Bit Field in C
  • Difference Between Struct and Typedef Struct in C
  • How to Use struct Alignment and Padding in C
  • How to Initialize Array of Structs in C
  • How to Return a Struct From Function in C
  • How to Allocate Struct Memory With malloc in C

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

Related Articles

  • Solve Coding Problems
  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators
  • Assignment Operators in C
  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

C structures.

  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

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.

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:

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

2. structure variable declaration after structure template, access structure members.

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

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.

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.

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

  • Using Assignment Operator.
  • Using Initializer List.
  • Using Designated Initializer List.

1. Initialization using Assignment Operator

2. initialization using initializer list.

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 .

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

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.

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.

2. Separate Structure Nesting

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

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.

Accessing Nested Members

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

Example of Structure Nesting

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

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

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:

  • Using #pragma pack(1)
  • Using __attribute((packed))__

Example of Structure Padding and Packing

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 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

 example of bit fields.

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:

  • 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.
  • It can also be used in data organization where a large amount of data can be stored in different fields.
  • Structures are used to create data structures such as trees, linked lists, etc.
  • 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

  • C Structures vs C++ Structure

Please Login to comment...

  • C-Structure & Union
  • shubham_singh
  • RishabhPrabhu
  • RajeetGoyal
  • SidharthSunil
  • sagartomar9927
  • vishalyadav3
  • shikharg1110
  • abhishekcpp
  • snehalsalokhe

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

C structs and Pointers

C Structure and Function

C Struct Examples

  • Add Two Complex Numbers by Passing Structure to a Function
  • Add Two Distances (in inch-feet system) using Structures

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

  • Define Structures

Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword is used.

Syntax of struct

For example,

Here, a derived type struct Person is defined. Now, you can create variables of this type.

Create struct Variables

When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables.

Here's how we create structure variables:

Another way of creating a struct variable is:

In both cases,

  • person1 and person2 are struct Person variables
  • p[] is a struct Person array of size 20.

Access Members of a Structure

There are two types of operators used for accessing members of a structure.

  • . - Member operator
  • -> - Structure pointer operator (will be discussed in the next tutorial)

Suppose, you want to access the salary of person2 . Here's how you can do it.

Example 1: C structs

In this program, we have created a struct named Person . We have also created a variable of Person named person1 .

In main() , we have assigned values to the variables defined in Person for the person1 object.

Notice that we have used strcpy() function to assign the value to person1.name .

This is because name is a char array ( C-string ) and we cannot use the assignment operator = with it after we have declared the string.

Finally, we printed the data of person1 .

  • Keyword typedef

We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables.

For example, let us look at the following code:

We can use typedef to write an equivalent code with a simplified syntax:

Example 2: C typedef

Here, we have used typedef with the Person structure to create an alias person .

Now, we can simply declare a Person variable using the person alias:

  • Nested Structures

You can create structures within a structure in C programming. For example,

Suppose, you want to set imag of num2 variable to 11 . Here's how you can do it:

Example 3: C Nested Structures

Why structs in c.

Suppose you want to store information about a person: his/her name, citizenship number, and salary. You can create different variables name , citNo and salary to store this information.

What if you need to store information of more than one person? Now, you need to create different variables for each information per person: name1 , citNo1 , salary1 , name2 , citNo2 , salary2 , etc.

A better approach would be to have a collection of all related information under a single name Person structure and use it for every person.

More on struct

  • Structures and pointers
  • Passing structures to a function

Table of Contents

  • C struct (Introduction)
  • Create struct variables
  • Access members of a structure
  • Example 1: C++ structs

Sorry about that.

Most Popular

10 days ago

Explaining New Line in C

12 days ago

What function do you need to call to ask the user of the program to enter text?

How to initialize a struct in c.

Logan Romford

Structures in the C programming language allow you to create complex data types that can store multiple variables of different data types. Initializing a struct correctly is crucial to ensure your program functions as expected . In this article, we will explore various ways to initialize a struct in C, using keywords such as “C Programming Language,” “struct in C,” and “Initialize struct in C.”

Before we dive into initialization techniques, let’s gain a clear understanding of structures in C. A struct is a user-defined data type that can hold variables of different data types. It’s like creating your own custom data container.

What Is a Struct?

A struct is a composite data type that groups related variables together. In the C Programming Language, it’s often used to represent real-world entities or concepts . For example, you can define a struct to represent a person’s information:

In the example above, we’ve defined a struct called “Person” with three member variables: “name,” “age,” and “gender.” Each member variable has its data type.

Initialization Techniques

Now that we understand the basics of structs in C let’s explore various techniques for initializing structs. We’ll use the keywords “Initialization at Declaration” and “Initialization using Designated Initializer” among others.

Initialization at Declaration

One common way to initialize a struct in C is to do so at the time of declaration. This means you assign values to the struct members when you define the struct variable.

In this example, we’ve declared a struct variable “person” of type “Person” and initialized it with values for the “name,” “age,” and “gender” members.

Initialization using Designated Initializer

Another powerful method for struct initialization is using designated initializers. This allows you to specify which members you want to initialize explicitly.

Here, we’ve created a struct “pet” and used designated initializers to set the values for the “name,” “age,” and “weight” members. The order of assignment doesn’t matter with designated initializers.

Initialized at Compile Time

You can also initialize a struct at compile time using the dot operator. This method directly assigns values to the members of structure variables.

In this example, we’ve defined a struct “student” and assigned values to its members separately.

Choosing the Right Initialization Method

The choice of which initialization method to use depends on your specific programming requirements and preferences. Here’s a quick summary to help you decide:

  • Initialization at Declaration : Use this method when you want to initialize a struct variable right when it’s declared, and you know all the member values.
  • Initialization using Designated Initializer : This method is useful when you want to initialize specific members and don’t care about the order.
  • Initialized at Compile Time : If you prefer initializing members separately or need to modify them later in your program, this approach is suitable.

In this article, we’ve explored different techniques to initialize a struct in C. We’ve learned about the significance of structures in the C Programming Language and how they allow us to create custom data types. The keywords “struct in C” and “Initialize struct in C” have been evenly distributed throughout the text to enhance its search engine optimization (SEO) value.

Understanding the various initialization methods and when to use them is essential for efficient and bug-free C programming . Whether you prefer initializing at declaration, using designated initializers, or initializing at compile time, you now have the knowledge to make informed decisions based on your project’s requirements.

What are the different techniques for initializing a struct in C?

Different techniques for initializing a struct in C include initializing at declaration, using designated initializers, and initializing at compile time . These techniques allow you to set values for struct members efficiently based on your programming needs.

What is the designated initializer method for struct initialization?

The designated initializer method for struct initialization in C involves specifying member names and values during initialization . This method allows you to initialize specific members of a struct without worrying about the order, making your code more readable and maintainable.

When should you use the dot operator for struct initialization in C?

Use the dot operator for struct initialization in C when you want to assign values to struct members individually after the struct variable is declared . It’s helpful when you need to modify or update member values later in your program, providing flexibility in struct initialization.

Is it possible to initialize a struct at compile time using the dot operator?

No, it is not possible to initialize a struct at compile time using the dot operator in C . The dot operator is used for assigning values to struct members after the struct variable is declared, making it a runtime initialization technique.

What are the best practices for struct variable initialization in C?

Best practices for struct variable initialization in C include initializing at declaration whenever possible to ensure all members are set from the start, using designated initializers for clarity and maintainability , and initializing members explicitly to avoid uninitialized variables and potential bugs in your code.

Follow us on Reddit for more insights and updates.

Comments (0)

Welcome to A*Help comments!

We’re all about debate and discussion at A*Help.

We value the diverse opinions of users, so you may find points of view that you don’t agree with. And that’s cool. However, there are certain things we’re not OK with: attempts to manipulate our data in any way, for example, or the posting of discriminative, offensive, hateful, or disparaging material.

Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

More from C Guides

New Line in C

14 days ago

User Input in C – Explained

Remember Me

What is your profession ? Student Teacher Writer Other

Forgotten Password?

Username or Email

Search anything:

Structure (struct) in C [Complete Guide]

Software engineering c programming c++.

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

A structure is defined as a collection of same/different data types. All data items thus grouped logically related and can be accessed using variables.

Table of contents:

Basics of Structure in C

  • Structure Declaration 2.1. Tagged Structure 2.2. Structure Variables 2.3. Type Defined Structures

Structure Initialization in C

Accessing structures in c, array of structure in c, nested structures in c.

Let us get started with Structure (struct) in C.

" Struct " keyword is used to identify the structure.

Memory Allocation

12-1

Always, contiguous(adjacent) memory locations are used to store structure members in memory.Consider above example to understand how memory is allocated for structures.

There are 5 members declared for structure in above program. In 32 bit compiler, 4 bytes of memory is occupied by int datatype. 1 byte each of memory is occupied by char datatype.

Memory is reserved only if the above definition is associated with variables.That is once the structure are defined,they have to be declared .Then only 56 bytes of memory space is reserved.

Structure Declaration

Structure can be declare using three different ways:

1: Tagged Structure 2: Structure Variables 3: Type Defined Structures

1: Tagged Structure

The structure name with tag name is called tagged structure.The tag name is the name of the structure.

  • Here studentDetails is the tag name.
  • To allocate the memory for the structure, we have to declare the variable as shown below

struct studentDetails Jack,Jonas;

Once the structure variables are declared, the compiler allocates memory for the structure, So 32 bytes are reserved for the variable Jonas and another 32 bytes are reserved for the variable Jack.The size of the memory allocated is the sum of size of individiual members

2: Structure Variables

It is possible to declare variables of a structure, either along with structure definition or after the structure is defined.

Structure variable declaration is similar to the declaration of any normal variable of any other data type.

6

Observe that 40 bytes of memory is allocated for the variable S1 and another 22 bytes of memory is allocated for the variable S2.

Note: We avoid this way of defining and declaring the structure variablesm because of the following reasons:

  • Without a tag,it is not possible to declare variables in later stages inside the functions.
  • It is not possible to use them as parameter in the function,because all the parameter have to be declared.
  • We can define them only in the beginning of the program.In such situations,they are treated as global variables.In the structured programming it is better to avoid the usage of global variables.

3: Typed-Defined Structure

The Structure definition associated with keyword typedef is called type-defined structure.This is the most powerful way of defining the structure

It can be initialized in various ways

Method 1 : Specify the initializers within the braces and seperated by commas when the variables are declared as shown below:

Method 2 : Specify the initializers within the braces and seperated by commas when the variables are declared as shown below:

We can access structure in two ways:

  • By . (memeber or dot operator)
  • By -> ( structure pointer operator)

The array of structures in C are used to store information about various member of different data types.It is also known as collection of structure.

Nested structure means structure within structure. As we have declared members inside the structure in the same we can declare declare structure.

With this article at OpenGenus, you must have a complete idea of structure (Struct) in C / C++ Programming Language.

OpenGenus IQ: Computing Expertise & Legacy icon

Table of Contents

Why do we use structures in c, syntax to define a structure in c, how to declare structure variables, how to initialize structure members, how to access structure elements, how to pass structures to functions in c, what is designated initialization, what is an array of structures, what is a structure pointer, nested structures, limitations of structure in c programming, final thoughts, what is structures in c and how to create it.

Structure in C

At times, during programming , there is a need to store multiple logically related elements under one roof. For instance, an employee’s details like name, employee number, and designation need to be stored together. In such cases, the C language provides structures to do the job for us. 

Structure_in_C_1

A structure can be defined as a single entity holding variables of different data types that are logically related to each other. All the data members inside a structure are accessible to the functions defined outside the structure. To access the data members in the main function, you need to create a structure variable.

Now, lets get started with Structure in C programming .

Want a Top Software Development Job? Start Here!

Want a Top Software Development Job? Start Here!

Structure in C programming is very helpful in cases where we need to store similar data of multiple entities. Let us understand the need for structures with a real-life example. Suppose you need to manage the record of books in a library. Now a book can have properties like book_name, author_name, and genre. So, for any book you need three variables to store its records. Now, there are two ways to achieve this goal. 

The first and the naive one is to create separate variables for each book. But creating so many variables and assigning values to each of them is impractical. So what would be the optimized and ideal approach? Here, comes the structure in the picture. 

We can define a structure where we can declare the data members of different data types according to our needs. In this case, a structure named BOOK can be created having three members book_name, author_name, and genre. Multiple variables of the type BOOK can be created such as book1, book2, and so on (each will have its own copy of the three members book_name, author_name, and genre). 

Moving forward, let’s he a look at the syntax of Structure in C programming

struct structName 

   // structure definition

   Data_type1 member_name1;

   Data_type2 member_name2;

   Data_type2 member_name2; 

Below is the description of Structure in C programming   

Description of the Syntax

  • Keyword struct: The keyword struct is used at the beginning while defining a structure in C. Similar to a union, a structure also starts with a keyword.
  • structName: This is the name of the structure which is specified after the keyword struct. 
  • data_Type: The data type indicates the type of the data members of the structure.  A structure can have data members of different data types.
  • member_name: This is the name of the data member of the structure. Any number of data members can be defined inside a structure. Each data member is allocated a separate space in the memory.

Next, let us see how to declare variable of structure in C programming

Prepare Yourself to Answer All Questions!

Prepare Yourself to Answer All Questions!

Variables of the structure type can be created in C. These variables are allocated a separate copy of data members of the structure. There are two ways to create a structure variable in C.

Declaration of Structure Variables with Structure Definition

This way of declaring a structure variable is suitable when there are few variables to be declared. 

   Data_type2 member_name2;   

} struct_var1, struct_var2;

struct bookStore

   char storeName

   int totalBooks;

   char storeLicense[20];

} storeA, storeB;   // structure variables

The structure variables are declared at the end of the structure definition, right before terminating the structure. In the above example, storeA and storeB are the variables of the structure bookStore. These variables will be allocated separate copies of the structure’s data members that are- storeName, totalBooks, and storeLicense.

Declaration of Structure Variables Separately

This way of creating structure variables is preferred when multiple variables are required to be declared. The structure variables are declared outside the structure. 

struct structName

   struct structName struct_var1, struct_var2;

   char storeName 

   char storeLicense[20]; 

   struct bookStore storeA, storeB; // structure variables;

When the structure variables are declared in the main() function, the keyword struct followed by the structure name has to be specified before declaring the variables. In the above example, storeA and storeB are the variables of the structure bookStore. 

Next, let us see how to initialize member in Structure in C programming

Structure members cannot be initialized like other variables inside the structure definition. This is because when a structure is defined, no memory is allocated to the structure’s data members at this point. Memory is only allocated when a structure variable is declared. Consider the following code snippet.

struct rectangle

   // structure definition 

   int length = 10;   // COMPILER ERROR:  cannot initialize members here.

   int breadth = 6;   // COMPILER ERROR:  cannot initialize members here. 

A compilation error will be thrown when the data members of the structure are initialized inside the structure. 

To initialize a structure’s data member, create a structure variable. This variable can access all the members of the structure and modify their values. Consider the following example which initializes a structure’s members using the structure variables.

   int length;   

   int breadth;   

   struct rectangle my_rect; // structure variables;

   my_rect.length = 10;

   my_rect.breadth = 6;

In the above example, the structure variable my_rect is modifying the data members of the structure. The data members are separately available to my_rect as a copy. Any other structure variable will get its own copy, and it will be able to modify its version of the length and breadth. 

Moving forward, let us understand how to access elements in structure in C programming

The members of a structure are accessed outside the structure by the structure variables using the dot operator (.). The following syntax is used to access any member of a structure by its variable:

structVariable.structMember

The following example illustrates how to access the members of a structure and modify them in C. 

#include <stdio.h>

#include <string.h>

struct cube

   // data members

   char P_name[10];

   int P_age;

   char P_gender;

   // structure variables

   struct cube p1, p2;

   // structure variables accessing the data members.

   strcpy(p1.P_name, "XYZ");

   p1.P_age = 25;

   p1.P_gender = 'M';

   strcpy(p2.P_name, "ABC");

   p2.P_age = 50;

   p2.P_gender = 'F';

   // print the patient records.

   // patient 1

   printf("The name of the 1st patient is: %s\n", p1.P_name);

   printf("The age of the 1st patient is: %d\n", p1.P_age);

   if (p1.P_gender == 'M')

      printf("The gender of the 1st patient is: Male\n");

      printf("The gender of the 1st patient is: Female\n");

   printf("\n");

   // patient 2

   printf("The name of the 2nd patient is: %s\n", p2.P_name);

   printf("The age of the 2nd patient is: %d\n", p2.P_age);

   if (p2.P_gender == 'M')

      printf("The gender of the 2nd patient is: Male\n");

      printf("The gender of the 2nd patient is: Female\n");

   return 0;

Structure_in_C_2

In the above program, a structure named Patient is defined. It has three data members- P_name, P_age, and P_gender. These data members have not been allocated any space in the memory yet. The variables p1  and p2 are the structure variables declared in the main function. 

As soon as these variables are created, they get a separate copy of the structure’s members with space allocated to them in the memory. Both p1 and p2 are accessing their copies of the structure’s members to modify them using the dot operator. 

Next, let us understand how to pass function in structure in C programming language

As all the members of a structure are public in C, therefore they are accessible anywhere and by any function outside the structure. Functions accept structures as their arguments in a similar way as they accept any other variable or pointer. To pass a structure to a function, a structure variable is passed to the function as an argument. 

A structure variable can be passed to a function as an argument in the following three ways:

Passing Structure to a Function by Value

When a structure variable is passed by its value, a copy of the members is passed to the function. If the function modifies any member, then the changes do not affect the structure variable’s copy of members. The following example illustrates how to pass a structure variable to a function by value in C.

struct patient

   char name[10];

   char gender;

// function that accepts a structure variable as arguments.

void passByValue(struct patient p)

   p.ID = 102; // this modification does not affect P1's id.

   // print the details.

   printf(" The patient's ID is: %d \n", p.ID);

   printf(" The patient's name is: %s \n", p.name);

   printf(" The patient's gender is: %c \n", p.gender);

   struct patient P1;

   P1.ID = 101;

   strcpy(P1.name, "ABC");

   P1.gender = 'M';

   passByValue(P1); // pass structure variable by value.

   // P1's ID remains unaffected by the function's modification.

   printf("\n The original value of ID is: %d\n\n", P1.ID);

Structure_in_C_3

In the above program, the function passByValue() accepts the structure’s variable P1 as an argument. This argument is passed by value. When the function makes a modification in the member ID, this modification does not affect the P1’s version of ID. The reason is that in the case of pass-by-value, only a copy of the members is passed to the function. So, any changes made by the function do not reflect in the original copy. 

Passing Structure to a Function by Reference

When a structure variable is passed by its reference, the address of the structure variable is passed to the function. This means the function does not get any copy, instead, it gets the reference or address of the structure variable’s members. 

If the function modifies any member, then the changes get reflected in the structure variable’s copy of members. Note that in pass-by-reference, the structure members can be accessed using the arrow operator (->).

The following example illustrates how to pass a structure variable to a function by reference in C.

void passByReference(struct patient *p)

   p->ID = 102; // this modification reflects P1's id.

   printf(" The patient's ID is: %d \n", p->ID);

   printf(" The patient's name is: %s \n", p->name);

   printf(" The patient's gender is: %c \n", p->gender);

   passByReference(&P1); // pass structure variable by reference.

   // P1's ID gets affected by the function's modification.

Structure_in_C_4.

In the above example, the function passByReference() accepts the structure’s variable P1 as an argument. This argument is passed by reference.  So, the function gets access to the location of the structure variable. When the function makes a modification in the member ID, this modification affects the P1’s version of ID. 

Declaring Structure Variables as Global

When a structure variable is declared as global, it can be accessed by any function in the program. There will be no need to pass the structure variable to the function. However, this is not advised as all the functions can modify the values of the structure variable’s copy of members. This also affects the data security in the program.

The following example illustrates how to declare a global structure variable in C and access it in functions.

// structure variable declared globally.

struct patient P1; 

void my_function()

   printf(" The patient's ID is: %d \n", P1.ID);

   printf(" The patient's name is: %s \n", P1.name);

   printf(" The patient's gender is: %c \n\n", P1.gender);

   // no need to pass the structure variable

   // to the function as an argument.

   my_function();   // function call

Structure_in_C_5

In the above example, the structure variable P1 is declared as a global variable. Being a global variable, P1 is accessed by any function in the program. The function my_function() does not require P1 to be passed to it as an argument. It can directly access P1 and modify any structure member using P1.

Moving forward,  let us understand what is designated initialization in structure in C programming language.

In the C99 standard, there is a unique feature that is not available in other standards like C90 or GNU C++. Designated initialization is supported for array, union, and structure in C. To understand the working of designated initialization, consider the following example of array initialization at the time of declaration.

int my_arr[5] = {10, 20, 30, 40, 50};

// my_arr[0] = 10, my_arr[1] = 20, ..., my_arr[5] = 50.

In the above array initialization, all array elements are initialized in the fixed order. This means that the element at index 0 is initialized first, then the index 1 element is initialized, and so on. 

These array elements can also be initialized in any random order, and this method is called designated initialization. Consider the following example which initializes the array elements in random order.

int a[5] = {[3] = 30, [2] = 20 }; 

int a[5] = {[3]30 , [2]20 };

The following program illustrates the designated initialization of a structure in C.

   int length, breadth, height;

   // Examples of initialization using designated initialization

   struct rectangle r1 = {.breadth = 10, .height = 5, .length = 6};

   struct rectangle r2 = {.breadth = 20};

   printf("The values of r1 are: \n");

   printf("length = %d, breadth = %d, height = %d\n", r1.length, r1.breadth, r1.height);

   printf("The values of r2 are: \n");

   printf("length = %d, breadth = %d, height = %d\n\n", r2.length, r2.breadth, r2.height);

Structure_in_C_6.

In the above example, the structure members- length, breadth, and height are initialized in a random order using the designated initialization. This type of initialization would throw an error in the compiler of other standards and even C++ does not support this functionality.

Suppose you need to store the details of students like name, class, and roll number in your database. Now, the first thing that comes to your mind would be to create a structure variable and access the student details. This method is practical for a few students only, but what if the total number of students is 100 or something. It is not convenient to create 100 separate structure variables for 100 students. In such cases, we use an array of structures.

Just like other data types (mostly primitive), we can also declare an array of structures. An array of structures acts similar to a normal array. However, there is one thing to be kept in mind and that is the name of the structure followed by the dot operator(.) and the name of the array has to be mentioned to access an array element.

The following example illustrates the working of the array of structures in C.

// structure definition

struct Student

    // data members

    char name[10];

    int marks;

// declare an array of the structure Student.

struct Student stu[3];

// function to read the values

// from the user and print them.

void print()

    // read input from the user.

    for (i = 0; i < 3; i++)

        printf("\nEnter the record of Student %d\n", i + 1);

        printf("\nStudent name: ");

        scanf("%s", stu[i].name);

        printf("Enter Marks: ");

        scanf("%d", &stu[i].marks);

    // print the details of each student.

    printf("\nDisplaying Student record\n");

        printf("\nStudent name is %s", stu[i].name);

        printf("\nMarks is %d", stu[i].marks);

    // function call

    print();

    return 0;

Structure_in_C_7

In the above example, we have created a structure Student that holds student names and marks. We have initialized an array stu of size 3 to get the names and marks of 3 students. Note that unlike the usual array in C, the array of structures in C is initialized by using the names of the structure as a prefix.

A pointer structure is a variable that holds the address of the memory block of the structure. It is similar to other pointer variables like a pointer to an int or a pointer to a float. Consider the following code snippet.

struct point

    // data member

   int num;

 int main()

    // struct1 variable var

    struct struct1 var;

    // pointer variable

    struct point *ptr = &var;

Here, var is the structure variable of struct1 and ptr is the pointer variable. The ptr is storing the address of the var. In the case of a pointer to a structure, the members can be accessed using the arrow (->) operator. The following example illustrates the pointer to a structure in C.

#include<stdio.h>

struct myStruct

   int x, y;

   struct myStruct var1 = {1, 2};  

   // var2 is a pointer to structure var1.

   struct myStruct *var2 = &var1;  

   // Accessing data members of myStruct using a structure pointer.

   printf("%d %d", var2->x, var2->y);

Structure_in_C_8

In the above example, the structure myStruct has a variable var1. The var2 is the pointer variable that stores the address of this structure variable.

The C programming language allows the nesting of the structure. This can be done by using one structure into the body of another structure. Nesting of multiple separate structures enables the creation of complex data types.

For instance, you need to store the information of multiple students. Now the data members of the structure may be student name, student class, and student roll number. Now class can have multiple subparts like standard, section, and stream. Such types of cases can use nested structures to a great extent. 

A structure in C can be nested in two ways:

By Creating a Separate Structure

We can create two separate, let's say struct1 and struct2 structures, and then nest them. If you want to nest struct2 in struct1, then it is necessary to create struct2  variable inside the primary structure i.e., struct1. The nested structure would be used as a data member of the primary structure. Consider the following code snippet.

// structure 2

struct struct2

    // data members of struct2

// structure 1

struct struct1

    // data members of struct1 

    // struct2 variable

    struct struct2 obj2; 

}obj1; // struct1 variable 

Here, struct1 is the primary structure and struct2 is the secondary one. It is clearly observable that the variable of struct2 is created inside struct1.

The following example illustrates the nesting of a structure in C by creating a separate structure.

struct class_details

    int standard;

    char section;

    char stream[20];

    char name[20];

    int roll_num;

    // nested structure 2 in structure 1

    // class_details variable Class

    struct class_details Class;

    // Student variable stu

    struct Student stu; 

    // read the input from user

    printf("Enter details of the student: \n");

    scanf("%s %d %d %c %c",

          &stu.name,

          &stu.roll_num,

          &stu.Class.standard,

          &stu.Class.section,

          &stu.Class.stream); 

    // display the input info

    printf("The Student's details are: \n");

    printf("Name: %s\nRoll_num: %d\nStandard: %d\nSection: %c\nStream %s: ",

           stu.name,

           stu.roll_num,

           stu.Class.standard,

           stu.Class.section,

           stu.Class.stream); 

Structure_in_C_9

In the above example, we created two structures, Student and class_details. The structure Student contains the basic information about the student while the structure class_details contains the information about the class of the student specifically. The class_details structure is nested inside the Student structure by creating the object inside it so that all the data members of the class_details can be accessed by the Student structure too. 

By Creating Embedded Structure

In this method, instead of creating independent structures, if create a structure within a structure. This takes the independence of a structure and makes it inaccessible as well as useless for other structures. However, in this way, you have to write less code and the program will be cleaner. Consider the following code snippet.

    // structure 2

    struct struct2

        // data members of struct2 

    } obj2; // struct2 variable 

} obj1;     // struct1 variable

Here, struct2 is created inside struct1 just like a data member, and the struct2 variable is also defined inside the primary structure.

The following example illustrates the nesting of a structure in C by creating an embedded structure.

    int roll_num; 

    struct class_details

        int standard;

        char section;

        char stream[20];

Structure_in_C_10

Here, the logic and the data members are exactly the same as in the previous example. The major difference here is that instead of creating a separate structure of details of the class, we created an embedded structure. You can observe that even though the methods are different, the outputs of both methods are exactly the same.

Up to this point in this article, it must be pretty clear to you how important and useful structures in C are. However, everything that possesses some advantages has some limitations as well and so do structures. In this section, we are going to discuss some of these limitations.

  • The struct data type can not be used as a built-in data type. If you try to use it as a built-in data type, the compiler will throw an error.
  • Arithmetic operators can not be implemented on structure variables. Consider the following code as an example.

struct number

    float x;

    struct number n1, n2, n3;

    n1.x = 4;

    n2.x = 3;

    n3 = n1 + n2;

Structure_in_C_11.

  • Data hiding is not possible in structures. Structure in C does not permit any data members to be hidden and allows every function to access them.
  • You can not define member functions inside a structure in C. Structure in C only allows the definition of data members inside it and prohibits functions.
  • The concept of access modifiers is absent in the C language. So data members in a structure are always public to all the functions outside that structure.
  • Structure in C does not permit the creation of static members and constructors inside its body.

That was all about Structure in C Programming.

Advance your career as a MEAN stack developer with the  Full Stack Web Developer - MEAN Stack Master's Program . Enroll now!

To sum up, in this article Structure in C Programming, you have learned the basics of a structure in C programming. You started with a small introduction to a structure in C and moved ahead to discuss the uses of a structure in C. Next, you learned about the syntax of structures, how to declare and initialize a structure in C, and how to access the elements of a structure in C.  

Moving ahead, in the Structure in C Programming article you learned other important concepts such as designated initialization of a structure in C, array of structures, and a pointer to a structure. You ended the article with a brief explanation of nested structures and limitations of a structure in C. 

Why stop here? You can try out Simplilearn’s 9-month certification training on Full Stack Web Development . In this course, you will be able to learn important software development aspects such as Agile methodologies , DevOps culture and other important web development tools such as Java and it’s frameworks including Hibernate, Spring, etc. You will learn CSS , HTML , JS , and all other important tools that will make you a professional full stack developer. 

If you have a knack for learning new technologies periodically, you should check out Simplilearn’s complete list of free online courses. If you have any queries in this “Structure in C Programming” article or suggestions for us, please mention them in the comment box and our experts answer them for you as soon as possible.

Happy Learning!

Recommended Reads

The Ultimate Guide to Creating Chatbots

Basics of C++ Struct: Syntax, Creating Instance, Accessing Variables, and More

Your One-Stop Solution to Trees in C#

Free eBook: Salesforce Developer Salary Report

Implementing Stacks in Data Structures

Get Affiliated Certifications with Live Class programs

Post graduate program in full stack web development.

  • Live sessions on the latest AI trends, such as generative AI, prompt engineering, explainable AI, and more
  • Caltech CTME Post Graduate Certificate

Automation Testing Masters Program

  • Comprehensive blended learning program
  • 200 hours of Applied Learning

Caltech Coding Bootcamp

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Declaration of structure variable

We can declare structure variables in different ways.

Declaring structure variable along with structure declaration

We can also declare many variables using comma (,) like below,

Declaring structure variable using struct keyword.

In general, we declare variables like,

<data type> variables;

In structure, data type is <struct name> . So, the declaration will be

<struct name> variables;

Initializing structure members

We can initialize the structrue members directly like below,

How to access the structure members?

To access structure members, we have to use dot (.) operator .

It is also called the member access operator .

To access the price of car1,

To access the name of car1,

Sample Program

We can also change the value of structure members using dot (.) operator or member access operator

Sample program

  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Structure declaration in C language

The structure is a collection of different datatype variables, grouped together under a single name. It is a heterogeneous collection of data items that share a common name.

Features of structure

It is possible to copy the contents of all structural elements of different data types to another structure variable of its type by using an assignment operator.

To handle complex datatypes, it is possible to create a structure within another structure, which is called nested structures.

It is possible to pass an entire structure, individual elements of structure, and address of structure to a function.

It is possible to create structure pointers.

The general form of structure declaration is as follows −

struct is the keyword.

tagname specifies the name of a structure

member1, member2 specifies the data items that makeup structure.

For example,

Structure variables

There are three ways of declaring structure variables, which are as follows −

Bhanu Priya

Related Articles

  • Explain the variable declaration, initialization and assignment in C language
  • Explain variable declaration and rules of variables in C language
  • What is union of structure in C language?
  • Explain linear data structure queue in C language
  • Declaring a structure with no members in C language
  • Explain the accessing of structure variable in C language
  • Structure of Human Language
  • Write a structure in local scope program using C language
  • Explain bit field in C language by using structure concept
  • What is a structure at local scope in C language?
  • How to access the pointer to structure in C language?
  • Write an example program on structure using C language
  • Phrase and Grammar structure in Natural Language
  • State the importance of C language and its general structure
  • Explain top-down design and structure chart of function in C language

Kickstart Your Career

Get certified by completing the course

cppreference.com

Constructors and member initializer lists.

Constructors are non-static member functions declared with a special declarator syntax, they are used to initialize objects of their class types.

In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members. (Not to be confused with std::initializer_list .)

[ edit ] Syntax

Constructors are declared using member function declarators of the following form:

Where class-name must name the current class (or current instantiation of a class template), or, when declared at namespace scope or in a friend declaration, it must be a qualified class name.

The only specifiers allowed in the decl-specifier-seq of a constructor declaration are friend , inline , constexpr (since C++11) , consteval (since C++20) , and explicit (in particular, no return type is allowed). Note that cv- and ref-qualifiers are not allowed either: const and volatile semantics of an object under construction don't kick in until the most-derived constructor completes.

The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list , whose syntax is the colon character : , followed by the comma-separated list of one or more member-initializers , each of which has the following syntax:

[ edit ] Explanation

Constructors have no names and cannot be called directly. They are invoked when initialization takes place, and they are selected according to the rules of initialization. The constructors without explicit specifier are converting constructors . The constructors with a constexpr specifier make their type a LiteralType . Constructors that may be called without any argument are default constructors . Constructors that take another object of the same type as the argument are copy constructors and move constructors .

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. The member initializer list is the place where non-default initialization of these subobjects can be specified. For bases that cannot be default-initialized and for non-static data members that cannot be initialized by default-initialization or by their default member initializer , if any (since C++11) , such as members of reference and const-qualified types, member initializers must be specified. (Note that default member initializers for non-static data members of class template instantiations may be invalid if the member type or initializer is dependent.) (since C++11) No initialization is performed for anonymous unions or variant members that do not have a member initializer or default member initializer (since C++11) .

The initializers where class-or-identifier names a virtual base class are ignored during construction of any class that is not the most derived class of the object that's being constructed.

Names that appear in expression-list or brace-init-list are evaluated in scope of the constructor:

Exceptions that are thrown from member initializers may be handled by function-try-block

Member functions (including virtual member functions) can be called from member initializers, but the behavior is undefined if not all direct bases are initialized at that point.

For virtual calls (if the direct bases are initialized at that point), the same rules apply as the rules for the virtual calls from constructors and destructors: virtual member functions behave as if the dynamic type of * this is the static type of the class that's being constructed (dynamic dispatch does not propagate down the inheritance hierarchy) and virtual calls (but not static calls) to pure virtual member functions are undefined behavior.

Reference members cannot be bound to temporaries in a member initializer list:

Note: same applies to default member initializer .

[ edit ] Initialization order

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

(Note: if initialization order was controlled by the appearance in the member initializer lists of different constructors, then the destructor wouldn't be able to ensure that the order of destruction is the reverse of the order of construction.)

[ edit ] Notes

[ edit ] example, [ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] References

  • C++23 standard (ISO/IEC 14882:2023):
  • 11.4.5 Constructors [class.ctor]
  • 11.9.3 Initializing bases and members [class.base.init]
  • C++20 standard (ISO/IEC 14882:2020):
  • 11.4.4 Constructors [class.ctor]
  • 11.10.2 Initializing bases and members [class.base.init]
  • C++17 standard (ISO/IEC 14882:2017):
  • 15.1 Constructors [class.ctor]
  • 15.6.2 Initializing bases and members [class.base.init]
  • C++14 standard (ISO/IEC 14882:2014):
  • 12.1 Constructors [class.ctor]
  • 12.6.2 Initializing bases and members [class.base.init]
  • C++11 standard (ISO/IEC 14882:2011):
  • C++98 standard (ISO/IEC 14882:1998):

[ edit ] See also

  • copy elision
  • converting constructor
  • copy assignment
  • copy constructor
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 12 February 2024, at 04:55.
  • This page has been accessed 2,715,075 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Learn C++

13.6 — Struct aggregate initialization

In the previous lesson ( 13.5 -- Introduction to structs, members, and member selection ), we talked about how to define structs, instantiate struct objects, and access their members. In this lesson, we’ll discuss how structs are initialized.

Data members are not initialized by default

Much like normal variables, data members are not initialized by default. Consider the following struct:

Because we have not provided any initializers, when joe is instantiated, joe.id , joe.age , and joe.wage will all be uninitialized. We will then get undefined behavior when we try to print the value of joe.id .

However, before we show you how to initialize a struct, let’s take a short detour.

What is an aggregate?

In general programming, an aggregate data type (also called an aggregate ) is any type that can contain multiple data members. Some types of aggregates allow members to have different types (e.g. structs), while others require that all members must be of a single type (e.g. arrays).

In C++, the definition of an aggregate is narrower and quite a bit more complicated.

Author’s note

In this tutorial series, when we use the term “aggregate” (or “non-aggregate”) we will mean the C++ definition of aggregate.

For advanced readers

To simplify a bit, an aggregate in C++ is either a C-style array ( 17.7 -- Introduction to C-style arrays ), or a class type (struct, class, or union) that has:

  • No user-declared constructors ( 14.9 -- Introduction to constructors )
  • No private or protected non-static data members ( 14.5 -- Public and private members and access specifiers )
  • No virtual functions ( 25.2 -- Virtual functions and polymorphism )

The popular type std::array ( 17.1 -- Introduction to std::array ) is also an aggregate.

You can find the precise definition of a C++ aggregate here .

The key thing to understand at this point is that structs with only data members are aggregates.

Aggregate initialization of a struct

Because a normal variable can only hold a single value, we only need to provide a single initializer:

However, a struct can have multiple members:

When we define an object with a struct type, we need some way to initialize multiple members at initialization time:

Aggregates use a form of initialization called aggregate initialization , which allows us to directly initialize the members of aggregates. To do this, we provide an initializer list as an initializer, which is just a braced list of comma-separated values.

There are 2 primary forms of aggregate initialization:

Each of these initialization forms does a memberwise initialization , which means each member in the struct is initialized in the order of declaration. Thus, Employee joe { 2, 28, 45000.0 }; first initializes joe.id with value 2 , then joe.age with value 28 , and joe.wage with value 45000.0 last.

Best practice

Prefer the (non-copy) braced list form when initializing aggregates.

In C++20, we can also initialize (some) aggregates using a parenthesized list of values:

We recommend avoiding this last form as much as possible, as it doesn’t currently work with aggregates that utilize brace elision (notably std::array ).

Missing initializers in an initializer list

If an aggregate is initialized but the number of initialization values is fewer than the number of members, then all remaining members will be value-initialized.

In the above example, joe.id will be initialized with value 2 , joe.age will be initialized with value 28 , and because joe.wage wasn’t given an explicit initializer, it will be value-initialized to 0.0 .

This means we can use an empty initialization list to value-initialize all members of the struct:

Const structs

Variables of a struct type can be const (or constexpr), and just like all const variables, they must be initialized.

Designated initializers C++20

When initializing a struct from a list of values, the initializers are applied to the members in order of declaration.

Now consider what would happen if you were to update this struct definition to add a new member that is not the last member:

Now all your initialization values have shifted, and worse, the compiler may not detect this as an error (after all, the syntax is still valid).

To help avoid this, C++20 adds a new way to initialize struct members called designated initializers . Designated initializers allow you to explicitly define which initialization values map to which members. The members can be initialized using list or copy initialization, and must be initialized in the same order in which they are declared in the struct, otherwise a warning or error will result. Members not designated an initializer will be value initialized.

For Clang users

When doing designated initializers of single values using braces, Clang improperly issues warning “braces around scalar initializer”. Hopefully this will be fixed soon.

Designated initializers are nice because they provide some level of self-documentation and help ensure you don’t inadvertently mix up the order of your initialization values. However, designated initializers also clutter up the initializer list significantly, so we won’t recommend their use as a best practice at this time.

Also, because there’s no enforcement that designated initializers are being used consistently everywhere an aggregate is initialized, it’s a good idea to avoid adding new members to the middle of an existing aggregate definition, to avoid the risk of initializer shifting.

When adding a new member to an aggregate, it’s safest to add it to the bottom of the definition list so the initializers for other members don’t shift.

Assignment with an initializer list

As shown in the prior lesson, we can assign values to members of structs individually:

This is fine for single members, but not great when we want to update many members. Similar to initializing a struct with an initializer list, you can also assign values to structs using an initializer list (which does memberwise assignment):

Note that because we didn’t want to change joe.id , we needed to provide the current value for joe.id in our list as a placeholder, so that memberwise assignment could assign joe.id to joe.id . This is a bit ugly.

Assignment with designated initializers C++20

Designated initializers can also be used in a list assignment:

Any members that aren’t designated in such an assignment will be assigned the value that would be used for value initialization. If we hadn’t have specified a designated initializer for joe.id , joe.id would have been assigned the value 0.

Initializing a struct with another struct of the same type

A struct may also be initialized using another struct of the same type:

The above prints:

Note that this uses the standard forms of initialization that we’re familiar with (copy, direct, or list initialization) rather than aggregate initialization.

This is most commonly seen when initializing a struct with the return value of a function that returns a struct of the same type. We cover this in more detail in lesson 13.8 -- Passing and returning structs .

guest

IMAGES

  1. Initializing Structure Variables in C Detailed Expalnation Made Easy

    struct declaration initialization c

  2. What Is Structures In C: How to Create & Declare Them

    struct declaration initialization c

  3. C

    struct declaration initialization c

  4. Unit4 C

    struct declaration initialization c

  5. Arrays in C#

    struct declaration initialization c

  6. C# : Struct initialization and new operator

    struct declaration initialization c

VIDEO

  1. C Pro Video 2: Declaration and Initialization of Pointers (Module 5)

  2. C++

  3. Lecture-08| Exploring Arrays concepts in C/C++ Programming| Declaration & Initializations

  4. Part-1

  5. Variables in C++

  6. C++ Functions Declaration, Definition and Calling [Hindi]

COMMENTS

  1. How to initialize a struct in accordance with C programming language

    How to initialize a struct in accordance with C programming language standards Ask Question Asked 15 years, 2 months ago Modified 16 days ago Viewed 1.3m times 616 I want to initialize a struct element, split in declaration and initialization. This is what I have:

  2. Struct and union initialization

    Struct and union initialization From cppreference.com < c ‎ | language C Program utilities Variadic function support Dynamic memory management Strings library Numerics Date and time utilities Input/output support Localization support Concurrency support Technical Specifications Symbol index [edit] C language Preprocessor History of C

  3. Struct declaration

    A struct is a type consisting of a sequence of members whose storage is allocated in an ordered sequence (as opposed to union, which is a type consisting of a sequence of members whose storage overlaps). type specifier for a struct is identical to the type specifier except for the keyword used: Syntax Explanation 3Forward declaration Keywords

  4. Initialize struct in C [3 ways]

    Basic steps to write a struct in C : Write the structure name following struct. You can decide the structure name as you like. Next, create a block with curly braces {}. Inside this block, define one or more variables that you want to use in your structure.

  5. How to declare, initialize and access structures in C language

    How to declare a structure? We use struct keyword to declare a structure. Let us declare a student structure containing three fields i.e. name, roll and marks. struct student { char name [100]; int roll; float marks; }; How to initialize a structure variable? C language supports multiple ways to initialize a structure variable.

  6. How to Initialize a Struct in C

    Use Constructors (in C99 and Later) to Initialize a Struct in C Conclusion Structs in C provide a powerful mechanism for grouping variables of diverse data types under a unified name. Properly initializing a struct is crucial for ensuring the correct functioning of your programs.

  7. C Structures

    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.

  8. C struct (Structures)

    Define Structures Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword is used. Syntax of struct struct structureName { dataType member1; dataType member2; ... }; For example, struct Person { char name [50]; int citNo; float salary; }; Here, a derived type struct Person is defined.

  9. How to Initialize a Struct in C: Step-by-Step Guide

    One common way to initialize a struct in C is to do so at the time of declaration. This means you assign values to the struct members when you define the struct variable. In this example, we've declared a struct variable "person" of type "Person" and initialized it with values for the "name," "age," and "gender" members.

  10. Initialization

    There is no special construct in C corresponding to value initialization in C++; however, ={0} (or (T){0} in compound literals)(since C99) can be used instead, as the C standard does not allow empty structs, empty unions, or arrays of zero length. The empty initializer ={} (or (T){} in compound literals) can be used to achieve the same ...

  11. Structure (struct) in C [Complete Guide]

    Structure Declaration. Structure can be declare using three different ways: 1: Tagged Structure 2: Structure Variables ... Structure Initialization in C. It can be initialized in various ways. Method 1: Specify the initializers within the braces and seperated by commas when the variables are declared as shown below:

  12. struct (C programming language)

    There are three ways to initialize a structure. For the struct type /* Declare the struct with integer members x, y */ struct point { int x; int y; }; C89-style initializers are used when contiguous members may be given. [4] /* Define a variable p of type point, and initialize its first two members in place */ struct point p = { 1, 2 };

  13. What Is Structures In C: How to Create & Declare Them

    A structure can be defined as a single entity holding variables of different data types that are logically related to each other. All the data members inside a structure are accessible to the functions defined outside the structure. To access the data members in the main function, you need to create a structure variable.

  14. Declaration and initialization of structure in c

    Declaration and initialization of structure in c | Member access operator Declaration of structure variable We can declare structure variables in different ways. Declaring structure variable along with structure declaration Syntax struct name / tag { //structure members } variables; Example struct car { char name [ 100 ]; float price; } car1;

  15. Structure declaration in C language

    There are three ways of declaring structure variables, which are as follows − Type 1 struct book { int pages; char author [30]; float price; }b; Type 2 struct { int pages; char author [30]; float price; }b; Type 3 struct book { int pages; char author [30]; float price; }; struct book b; Bhanu Priya Updated on: 08-Mar-2021 11K+ Views

  16. struct

    7,016 6 36 44 24 Personal view of the world: you don't need this style of object initialization in C++ because you should be using a constructor instead. - Philip Kendall Jul 17, 2012 at 5:50 7 Yes I thought of that, but I have an array of big Structure.

  17. C

    C 1972 Structure Initialization. Generally, the initialization of the structure variable is done after the structure declaration. Just after structure declaration put the braces (i.e. {}) and inside it an equal sign (=) followed by the values must be in the order of members specified also each value must be separated by commas.

  18. Constructors and member initializer lists

    Constructors and member initializer lists. Constructors are non-static member functions declared with a special declarator syntax, they are used to initialize objects of their class types. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.

  19. c++

    How to assign a C struct inline? Ask Question Asked 13 years ago Modified 1 year, 8 months ago Viewed 81k times 70 typedef struct { int hour; int min; int sec; } counter_t; And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like:

  20. 13.6

    Aggregate initialization of a struct Because a normal variable can only hold a single value, we only need to provide a single initializer: int x { 5 }; However, a struct can have multiple members: struct Employee { int id {}; int age {}; double wage {}; };

  21. how to initialize a static struct in c++?

    how to initialize a static struct in c++? Ask Question Asked 12 years, 10 months ago Modified 7 years, 5 months ago Viewed 43k times 10 I have managed to initialize correct any variable of basic type (i.e. int, char, float etc) but when declaring a little complex variable all i can see is errors. In the header file timer.h i declare