Struct Copy & Comparison

Copy structure means copying all variables of a structure to another structure. Structure comparison means comparing all variables of a structure to another structure.

Structure Copy

We can copy the structure variable directly using ‘=’ sign, only if both source and destination variables are of the same structure. Means both structure variables must be variables of the same structure.

If we try to copy structure variables of the different structures directly using’=’ sign then it will show an error. In that case, we have to assign values manually one by one using “.” operator.

Here destination structure means to whom we want to store/copy data of another variable, and that other structure variable is called source structure variable. Syntax to copy structure is as written below.

<destination structure variable>=<source structure variable>;
Example program of structure copy

In the below example program, there is a structure str. It has two structure variables str1, str2. Values are given to str1 and using “=” sign we are copying str1 to str2. And then we are printing members of both structure variables.

#include<stdio.h>
#include<conio.h>
struct str{		
int a;
char b;
}str1={1,'c'};
void main()
{ 
  struct str str2;	
  clrscr();
  str2=str1;
  printf("str1 : a = %d , b = %c \n",str1.a,str1.b);
  printf("str2 : a = %d , b = %c ",str2.a,str2.b);
  getch();
}

Output:

 

 

Structure comparison

We can not compare structure variables using relational operators like<,<=,>,>=,==. It shows an error if we do this. Here we have to compare structure members manually one by one using “.” operator. Let us understand by the below program.

Example program of passing structure member through function.

In the below example program, there are two structures named str, STR and their variables are str1, STR1 respectively. Member of str1 is ‘a’, having value 1. Member of STR1 is A, having value 3. 

  • As we can not use relational operators like =, <=, >=, <, >  directly, below in the manual method. In the manual method, we are comparing members of both structures using the dot “.” operator. And while accessing members, we are using relational operators.
#include<stdio.h>
#include<conio.h>

struct str{		
  int a;
}str1={1};

struct STR{		
  int A;
}STR1={3};

void main()
{
  struct str str2;	
  clrscr();
  if(str1.a > STR1.A)
    printf("a>A");
  else if(str1.a < STR1.A)
    printf("a<A");
  else
    printf("a=A");
  getch();
}

Output:

Learning from this blog:

  1. Meaning and syntax of copy structure.
  2. Which variable can be copied and which not.
  3. Meaning and syntax of compare structure.
  4. The problem is directly comparing structure and other ways as a solution.
  5. Program of copy and compare structure.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments