【C语言复习】结构体、共用体

文章目录

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);
}

如何计算结构体的大小。

一般不会考虑字节对齐的影响(因为太复杂,成员位置先后会受到影响)。

浅谈Struct结构体大小和存放地址

#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那行的内容
  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值