C语言的结构体和共同体的区别是什么?

Python013

C语言的结构体和共同体的区别是什么?,第1张

结构体(structure)是一种构造类型,它是由若干“成员”组成的。每一个成员可以是一个基本数据类型或者又是一个构造类型,而且每个成员的数据类型可以相同也可以不相同。共同体(union)将几种不同的变量储存在同一内存单元中,也就是使用覆盖技术,几个变量互相覆盖,这种几个不同的变量共同占用一段内存的结构,可见二者最大的区别就是所占用的内存,结构体(structure)所占用的内存是分量内存之和,共同体(union)所占用的内存是等于最大的分量的内存。

具体来说,结构体(structure)与共同体(union)主要有以下区别:

1.结构体(structure)与共同体(union)都是由多个不同的数据类型成员组成,

但在任何同一时刻,

共同体(union)中只存放了一个被选中的成员,

而结构体(structure)的所有成员都存在。在结构体(structure)中,各成员都占有自己的内存空间,它们是同时存在的。一个结构体(structure)变量的总长度等于所有成员长度之和。在共同体(union)中,所有成员不能同时占用它的内存空间,它们不能同时存在。共同体(union)变量的长度等于最长的成员的长度。

2.

对于共同体(union)的不同成员赋值,

将会对其它成员重写,

原来成员的值就不存在了,

而对于结构体(structure)的不同成员赋值是互不影响的。

首先你说的很对 共同体的确占的内存要比结构体小

结构体占用的内存空间,是其元素,占空间的总和,而共用体是,元素中占用空间最大的元素的空间!所以共用体在空间开销上要小一点!

但是既然是两个不同的概念当然是不一样的 要不就没必要定义两个名词了

其实在共用体所用的内存中已经写入了数据!当使用其它元素时!上次使用的内容将被覆盖. 也就是说他使几个不同类型的变量共占一段内存(相互覆盖),每次只有一个能使用

结构体则不然, 每个成员都会有存储空间的,可以一起用.内部变量间是相互独立的,c中的结构体和C++里的类很相像~~

#include<stdio.h>

#include<stdlib.h>

struct student{

int number

char name[15]

double score[3]

}

void Display_All(struct student * p,int count)

void Display_Average(struct student * p_student,int count)

int cmp(const void *a,const void *b)

void main()

{

int i=0

int count_student

printf("how many student:\n")

scanf("%d",&count_student)

struct student * p_student=malloc(sizeof(struct student)

*count_student)

printf("please enter student's data:\n")

//从键盘输入学生们的数据

for(i=0i<count_studenti++)

{

printf("number:")

scanf("%d",&(p_student+i)->number)

printf("name:")

scanf("%s",(p_student+i)->name)

printf("first score:")

scanf("%lf",&(p_student+i)->score[0])

printf("second score:")

scanf("%lf",&(p_student+i)->score[1])

printf("third score:")

scanf("%lf",&(p_student+i)->score[2])

}

//输出成绩报表

Display_All(p_student,count_student)

Display_Average(p_student,count_student)

}

int cmp(const void *a,const void *b)

{

return (((struct student*) a)->score[0]+((struct student*) a)-

>score[1]+((struct student*) a)->score[2])/3>(((struct student*) b)->score

[0]+((struct student*)b)->score[1]+((struct student*) b)->score[2])/3?-1:1

}

//并输出成绩报表(包括每人的学号,姓名,三门成绩及平均分数)

void Display_All(struct student* p_student,int count)

{

int i=0

printf("number name first_score second_score third_score

average_score\n")

for(i=0i<counti++)

{

printf("%-8d%-10s%-13lf%-14lf%-14lf%-14lf\n",(p_student

+i)->number,(p_student+i)->name,(p_student+i)->score[0],(p_student+i)-

>score[1],(p_student+i)->score[2],((p_student+i)->score[0]+(p_student+i)-

>score[1]+(p_student+i)->score[2])/3)

}

}

//输出平均分在前五名的学生姓名及平均成绩

void Display_Average(struct student * p_student ,int count)

{

int i

qsort(p_student,count,sizeof(struct student),cmp)

printf("nameaverage_score\n")

for(i=0i<2i++)

{

printf("%-8s%-lf\n",(p_student+i)->name,((p_student+i)-

>score[0]+(p_student+i)->score[1]+(p_student+i)->score[2])/3)

}

}