C语言 : 结构体

xiaoxiao2025-07-23  33

声明结构:

struct tag { member-list ; } variable-list ;

member-list 包含每个成员的类型和名字

tag ----标签字段------ 该结构体 类型的名字 variable-list —变量列表 -----该结构体类型 的一个或者多个变量

struct SIMPLE { int a ; char b ; float c; } ; struct SIMPLE x; struct SIMPLE y[20],*z;

相当于:

struct { int a ; char b ; float c; } x ; struct { int a ; int b ; float c ; } y[20] , *z ;

使用 typedef

typedef struct { int a ; int b ; float c ; } Simple ; Simple 是一个类型名称,而不是结构标签,SIMPLE 是一个 结构标签 后续的声明 是这个样子: Simple x ; Simple y[20] , *z ;

错误的方法

struct { int a ; int b ; float c ; } Basic ; struct Basic x ;

这个样子是错误的,因为Basic 是一个结构体变量。而不是一个结构体类型。 下面这个样子是正确的:

struct Basic { int a ; int b ; float c ; } ; struct Basic x ; x.a = 123 ;

结构体 作为函数参数

#define PRODUCT_SIZE 10 typedef struct { char product[PRODUCT_SIZE]; int quantity ; float unit_price ; float total_amount ; }Transaction; void print_receipt(Transaction trans) { printf("%s\n",trans.product); } int main(void) { Transaction current_trans ; print_receipt(current_trans); }
这个方法能够产生正确的结果,但是效率很低。

因为C语言是参数传值调用的方式,要求把参数的一份拷贝传递给函数。 如果PRODUCT_SIZE 为20 ,整形和浮点型占4个字节。 那么结构体将占据32个字节的空间。 把结构体作为参数传递,必须把32个字节复制到堆栈中,使用之后再丢弃。

结构体指针 作为参数

#define PRODUCT_SIZE 10 typedef struct { char product[PRODUCT_SIZE]; int quantity ; float unit_price ; float total_amount ; }Transaction; void print_receipt(Transaction const * trans) { printf("%s\n",trans->product); } int main(void) { Transaction current_trans ; print_receipt(&current_trans); }

const 防止对结构体变量 进行修改 如果需要修改结构体变量的时候,就不要加上const。

以上来自 《C和指针》 Page209

函数 返回 类型 结构体

typedef struct { U8 second; U8 minute; U8 hour; } RTCMember; RTCMember tTCMember; RTCMember rtc_soft_read(void) { return(tTCMember); }

这样做有什么好处吗?

和使用指针比较?

返回值应该是 拷贝

转载请注明原文地址: https://www.6miu.com/read-5033592.html

最新回复(0)