1.结构体
其实就是各种不同/相同类型的变量放在一个盒子里面使用。常见的就是一个学生,有多门课程的成绩,需要统计,就可以方便使用。和JAVA、C++等面向对象中的一个class类相似,但是范围欠佳。毕竟C语言是面向过程的算法。
//不同的声明方式
struct{
int a;
char b;
double c;
} s1;
struct s2{
int a;
char b;
double c;
};
typedef struct{
int a;
char b;
double c;
} S3;
S3 u1,u2[20],*u3;
结构体变量的初始化
#include <stdio.h>
struct Books{
char title[50];
char author[50];
char subject[100];
int book_id;
} book = {"C 语言", "RUNOOB", "编程语言", 123456};
int main(){
printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book.title, book.author, book.subject, book.book_id);
} //注意输出格式
访问方式就很简单
struct Books Book1;
/* 声明 Book1,类型为 Books */
Book1.title="C 语言";
传参也一样的
getStruct(Book1);//main函数体中 调用函数
void getStruct( struct Books book)
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
如何计算结构体的大小。
一般不会考虑字节对齐的影响(因为太复杂,成员位置先后会受到影响)。
#include <stdio.h>
struct Person {
char name[20];
int age;
double height;
};
int main() {
struct Person person;
printf("结构体 Person 大小为: %zu 字节\n", sizeof(person));
//结构体 Person 大小为: 32 字节
//20+4+8
//float是4字节 double是8字节
return 0;
}
2.共用体
允许您在相同的内存位置存储不同的数据类型。可以定义一个带有多成员的共用体,但是任何时候只能有一个成员带有值。共用体提供了一种使用相同的内存位置的有效方式。
#include <stdio.h>
#include <string.h>
union Data{
int i;
float f;
char str[20];
};
int main( ){
union Data data;
printf( "数据占用内存大小为 : %d\n", sizeof(data));
//数据占用内存大小为 :20
return 0;
}
#include <stdio.h>
#include <string.h>
union Data{
int i;
float f;
char str[20];
};
int main( ){
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
//注意输出内容:
/*
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
*/
只会得到最后对共用体赋值的值 即strcpy那行的内容