比较结构变量的C程序
在C编程语言中,结构是不同数据类型变量的集合,这些变量组合在一个名称下。
结构的声明和初始化
结构声明的一般形式如下-
datatype member1;
struct tagname{
datatype member2;
datatype member n;
};这里,
struct是一个关键字。
tagname指定结构的名称。
member1、member2指定构成结构的数据项。
例如,
struct book{
int pages;
char author [30];
float price;
};结构变量
有三种声明结构变量的方法,如下所示-
第一种方法
struct book{
int pages;
char author[30];
float price;
}b;第二种方法
struct{
int pages;
char author[30];
float price;
}b;第三种方法
struct book{
int pages;
char author[30];
float price;
};
struct book b;结构的初始化和访问
成员和结构变量之间的链接是通过使用成员运算符(或)点运算符建立的。
初始化可以通过以下方法完成-
第一种方法
struct book{
int pages;
char author[30];
float price;
} b = {100, “balu”, 325.75};第二种方法
struct book{
int pages;
char author[30];
float price;
};
struct book b = {100, “balu”, 325.75};使用成员运算符的第三种方法
struct book{
int pages;
char author[30];
float price;
} ;
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75;示例
以下是用于比较结构变量的C程序-
struct class{
int number;
char name[20];
float marks;
};
main(){
int x;
struct class student1 = {001,"Hari",172.50};
struct class student2 = {002,"Bobby", 167.00};
struct class student3;
student3 = student2;
x = ((student3.number == student2.number) &&
(student3.marks == student2.marks)) ? 1 : 0;
if(x == 1){
printf("\nstudent2 and student3 are same\n\n");
printf("%d %s %f\n", student3.number,
student3.name,
student3.marks);
}
else
printf("\nstudent2 and student3 are different\n\n");
}输出结果执行上述程序时,它会产生以下输出-
student2 and student3 are same 2 Bobby 167.000000