Initializing and Assignment of Structure in C Language with Free Notes

Initializing a Structure

When a Structure variable is Declared, its data member are not initialized and therefore contain undefined values. Similar to simple Variables and Arrays, the Structure variables can also be initialized.

For Instance the Structure can be declared and initialized as shown below: –

struct student 
{
   char name [20];
   int age;
   int roll;
   char class[5];
};
strcut student s1 = {"Pawanpreet", 21, 1251, "BSC"};

The Values are assigned to the members of the structure in order of their appearance i.e. first value is assigned to the first member, second to second and so on.

Free Hand-Written Notes

Assignment of Structure

The value of one Structure variable can be assigned to another variable of the same type using simple assignment statement. For Example, if two Structure variables s1 and s2 have been declared as shown below: –

struct student s1, s2;

then the following assignment statement is perfectly valid.

s2 = s1;

This statement will perform the necessary internal assignments. The concept of Structure assignment can be better understood by the following example program.

Example: Demonstration of assignment of complete Structure

#include<stdio.h>
#include<conio.h>
void main()
{
  struct student
     {
      char name [20];
      int age;
      int roll;
      char class[5];
     }
      s1 = {"Pawanpreet", 21, 1251, "BSC"}, s2;
      clrscr();
      
      //Assign the Structure s1 to s2
      s2=s1;
      printf("\n The assigned values are...\n");
      printf("\n%s\t%d\t%d\t%s", s2.name, s2.age, s2.roll, s2.class),
    getch(),
}

Output

The assigned values are...
Pawanpreet 21 1251 BSC 

Leave a Comment

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

Scroll to Top