鱼C论坛

 找回密码
 立即注册
查看: 2474|回复: 3

给结构体字符串赋值,之前也是这么做的,这次怎么报错了

[复制链接]
发表于 2021-1-15 18:51:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include<winuser.inl>
  2. #include<stdio.h>
  3. #include <cstdlib>
  4. #include<string.h>

  5. union Test
  6. {
  7.         int i;
  8.         double pi;
  9.         char *str;
  10. };

  11. int main()
  12. {
  13.         union Test test;
  14.         test.i = 520;
  15.         test.pi = 3.14;
  16.         test.str = "fishc";

  17.         printf("address of test.i: %p\n", &test.i);
  18.         printf("address of test.pi: %p\n", &test.pi);
  19.         printf("address of test.str: %p\d",&test.i);
  20.         return 0;
  21. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-1-15 18:57:05 | 显示全部楼层
1、union 不是结构体,结构体是struct ,union 中文叫联合。
2、 printf("address of test.str: %p\d",&test.i);   \d 不是转义符。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-1-15 19:00:54 | 显示全部楼层
xieglt 发表于 2021-1-15 18:57
1、union 不是结构体,结构体是struct ,union 中文叫联合。
2、 printf("address of test.str: %p\d",&tes ...

不是这个地方的问题,我改过了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-1-15 19:08:36 | 显示全部楼层
本帖最后由 jackz007 于 2021-1-15 19:54 编辑

      即便是结构体,也只是支持定义时初始化,不可以在运行时整体赋值,主要是不可以通过等号为字符串成员赋值。
      联合是多个成员共用同一块内存,通常是为其中的某一个成员赋值,其它成员自动就会获得赋值,没有必要对所有成员一一赋值,每次新的赋值都是对前面赋值的否定和覆盖。
      楼主可以试一下这个代码:
  1. #include <stdio.h>

  2. union Test {
  3.         int i     ;
  4.         char c[4] ;
  5. }                 ;

  6. int main(void)
  7. {
  8.         union Test test = {0x44434241}                       ;  // 初始化的是整个联合体,而不是哪一个成员
  9.         int i                                                ;
  10.         printf("%x\n" , test . i)                            ;  // 按十六进制整型数显示 test . i
  11.         for(i = 0 ; i < 4 ; i ++) printf("%c" , test . c[i]) ;  // 按字符显示 test . c
  12.         printf("\n")                                         ;
  13. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-2 20:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表