fbpx

Different Ways to Initialize Structures in C


INTRODUCTION

In C programming, structures are a powerful tool that allow developers to define custom data types that group different data elements under one name. Unlike arrays, which store elements of the same type, structures can combine multiple data types, making it easier to handle and organize related information. This versatility is crucial for applications requiring complex data management, like embedded systems, user interfaces, and hardware programming.

C structures create a template for data grouping, enabling the declaration of variables with diverse data members, such as integers, characters, and floating-point values, all in one unified format. However, managing structures requires familiarity with key concepts, including how to declare and initialize structure variables, access members, and use different initialization methods like assignment operators, initializer lists, and designated initializers.

  • Structure is a user defined datatype.
  • Collection of different data type. The data type may not be same.

C Structure Declaration:

Structure in C:

Structure representation and its data members.

struct employee;

{

char_name [10];

int empno [6];

float salary;

};emp1,emp2;

Syntax for structure

Struct structure_name

{

datatype member1;

datatype member2;

datatype member3;

}                                                                                                                            

2. Structure Variable Declaration after Structure Template

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

Access Structure Members

dot operator(.) used to access structure members.

Syntax:

structure_name.member1;
strcuture_name.member2;

 

Initialize Structure Members

When we are declaring structure members cannot be initialized

The C program fails in the compilation.

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

 

 

  • The structure only provides a template, so initializing members in the declaration would imply that every instance of the structure should have default values,
  • which conflicts with C’s approach to flexible memory manag

Default Initialization

  • Automatically not initialized to zero in case of structures
  • Uninitialized structure members will hold arbitrary (garbage) values.
  • However, if a structure variable is created with an initializer, members that are not explicitly initialized are automatically set to zero.

Three different ways to intilialize the structure.

  1. Using Assignment Operator.
  2. Using Initializer List.
  3. Using Designated Initializer L
  • Using Assignment Operator:

Struct structure_name str;

 str.member1=value;

str.member2=value;

str.member3=value;

  • Using initializer list:
  • Struct struct_name={value1;value2;value3};

3.Using Designated Initializer List:

 

Struct struct_name={.member1=value;.member2=value;.member3=value};

 

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

    struct str1 v1 = { 1, ‘A’, 1.00 },

                v2;

    struct str2 v3 = { .ff = 23.00, .ii = 7, .cc = ‘a’ };

 

    // copying structure using assignment operator

    v2 = v1;

 

    printf(” %d,  %c,  %f\n”,

           v1.i, v1.c, v1.f);

    printf(“%d,  %c,  %f\n”,

           v2.i, v2.c, v2.f);

    printf(” %d,  %c,  %f\n”, v3.ii,

           v3.cc, v3.ff);

 

    return 0;

}

Example 2:

 

#include<Stdio.h>

struct point

{

int x;

int y;

};

int main()

{

struct  point str;

str.x=10;

str.y=20;

struct point pt={40,50};

struct point pt1={.x=60,.y=70};

printf(“%d\t%d\n”,pt.x,pt.y);

printf(“%d\t%d”,pt1.x,pt1.y);

 

}

 

Typedef for Structures:

 

  • typedef is used to create an alternate name for an existing data type.
  • The typedef keyword allows defining an alternative name for an already existing data type.
  • In structures, the struct keyword must be used alongside the structure name when defining variables, which can sometimes make the code longer and more complex. However, we can simplify this by using typedef to create a new, shorter name for the structure.

 

// Describles the use of typedef with

// structures

#include <stdio.h>

// defining structure

typedef struct {

    int a;

} str1;

 

typedef struct {

    int x;

} str2;

int main()

{

    // creating structure variables using new names    // here instead  of creating a struct followed by structname followed by variablename we used to declare by using typedef;

    str1 v1 = { 20 };

    str2 v2 = { 314 };

    printf(“v1.a = %d\n”, v1.a);

    printf(“v2.x = %d\n”, v2.x);

    return 0;

}

Nested structures: (structures within the structure)

  • Purpose: To logically group related data, making it easier to handle complex data relationships.
  • Access: Members of a nested structure are accessed using the dot operator (.) through the outer structure instance.

struct address

{

int streetno[5];

char city[12];

int zipcode[6];

}

 

typedef struct student{

Int studentno[5];

Char studentname[20];

Struct Address address;

}stu;

#include<stdio.h>

int main()

{

stu s1;

printf(“Enter the student no”);

scanf(“%d”,&s1.studentno);

printf(“Enter the studentname”);

scanf(“%d”,&s1.studentname);

printf(“Enter the address”);

 

scanf(“%d”,&s1.address.streetno);

return 0;

}