Question:
How can we check whether the contents of two structure variables are same or not?
Answer:
Source: CoolInterview.com
There is no way to compare entire structure, we can only compare element by element. example: typedef struct{ int a; int b; } ravi_t; main() { ravi_t r; ravi_t s; /* this is not allowed */ if(r==s) /* this is not allowed */; /* where as we can compare element by element */ if(r.a == s.a); Source: CoolInterview.com
Answered by: Ravikiran | Date: 6/1/2008
| Contact Ravikiran
The two structure variables need to be of same type. we can check the equality of two structure variables by comparing them individually. example:: #include<stdio.h> #include<conio.h> struct student { int rno; char name[20]; float tot; }a,b; void main() { clrscr(); printf("enter rno,total of student 1"); scanf("%d%f",a.rno,a.total); printf(" enter the name of student1"); scanf("%s",a.name); printf(" enter the rno and total of student2"); scanf("%d%f",b.rno,b.total); printf(" enter the name of student2"); scanf("%s",b.name);
if((a.rno==b.rno)&&(a.name==b.name)&&(a.total==b.total)) printf(" two structure variables are equal"); else printf(" two structure variables are not equal"); getch(); } Source: CoolInterview.com
Answered by: kishore reddy | Date: 6/1/2008
| Contact kishore reddy
The only possible way is through by checking every element by element. Source: CoolInterview.com
Answered by: saisatish | Date: 6/23/2008
| Contact saisatish
One more method,
convert two structure pointer as (char *) anyway we know the size so we could compare byte by byte. Source: CoolInterview.com
Answered by: jothikumar | Date: 7/9/2008
| Contact jothikumar
use memcmp().
eg: #include <stdio.h> typedef struct { int a; float f; }Struct;
int main() { Struct s1,s2; s1.a = 25; s1.f = 3.55; s2.a = 25; s2.f = 4.55; if(0 == memcmp(&s1,&s2,sizeof(s1))) { printf(" Equal "); } else printf(" Not Equal ");
getchar(); return 0; } Source: CoolInterview.com
Answered by: Vara | Date: 11/24/2009
| Contact Vara
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|