关于结构体变量赋初值和相同类型的结构体变量之间直接赋值的问题

I'mAlex
嵌入式领域新星创作者
2012-10-25 07:42:33
结构体:
typedef struct{
char mark;
int score;
int id;
}test_t;


1.结构体变量可以整体初始化,但是不能整体赋初值。

struct test test1 = {1,’B’,80.5};  //整体初始化。√
struct test test1; //结构体变量的声明
test1 = {1,’B’,80.5}; //整体赋初值。×

2.相同类型的结构体变量之间是可以直接进行赋值操作的。

那么,下面这段程序怎麽解释?下面的操作是可以的。
typedef struct{
   int score;
   int id;
  }test_t;
test_t test1 = {90, 200902};
test_t test2;
test2 = test1;

其中
test_t test1 = {90, 200902};  //定义(声明+初始化)
test_t test2; //声明
test2 = test1; //相同类型的结构体变量直接赋值操作,也是对test2的赋初值操作

test2 = test1;
问题1.这里是对test2的赋初值,这样为什么就可以了呢?这里面涉及到了什么问题?
问题2.既然相同类型的结构体变量直接赋值操作,那么结构体变量就可以作为函数参数和返回值来使用了,作为参数传递时,将结构体整体赋给相同类型的形参,也算是对形参的赋初值了,这样为什么也可以呢?
其实,这俩是同一个问题。
...全文
2083 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
I'mAlex 2012-10-31
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 的回复:]
C99是支持的

ISO/IEC 9899:1999 (E) ©ISO/IEC
6.5.16.1 Simple assignment
Constraints
1 One of the following shall hold:93)
— the left operand has qualified or unqualified arithmetic type and the right……
[/Quote]
我刚用VC6试了下,也不报错。应该是C99的问题。
不会传图片。就不传了。
VC6下的程序:
#include <stdio.h>

typedef struct{
int score;
int id;
}test_t;

int main(void)
{
test_t test1 = {90, 200902};
test_t test2;
test2 = test1;
}
startservice 2012-10-27
  • 打赏
  • 举报
回复
C99是支持的

ISO/IEC 9899:1999 (E) ©ISO/IEC
6.5.16.1 Simple assignment
Constraints
1 One of the following shall hold:93)
— the left operand has qualified or unqualified arithmetic type and the right has
arithmetic type;
— the left operand has a qualified or unqualified version of a structure or union type
compatible with the type of the right;
— both operands are pointers to qualified or unqualified versions of compatible types,
and the type pointed to by the left has all the qualifiers of the type pointed to by the
right;
— one operand is a pointer to an object or incomplete type and the other is a pointer to a
qualified or unqualified version of void, and the type pointed to by the left has all
the qualifiers of the type pointed to by the right; or
— the left operand is a pointer and the right is a null pointer constant.
— the left operand has type _Bool and the right is a pointer.
驴被脑袋踢了 2012-10-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

引用 3 楼 的回复:

结构体用错了吧!先把书上基础知识看看

我觉得你确实需要需要先把书上基础知识看看。
这里面涉及到的东西,全部都是对的。
最烦的就是你这种人,我猜你都不知道我说的啥
[/Quote]
LZ不要为这种人恼火,直接认为标准就这么规定的,然后记住,呵呵
AnYidan 2012-10-27
  • 打赏
  • 举报
回复 1
1. 区分 初始化 和 赋值

2。结构体支持 赋值,可以当参数传递 并 可以被返回
I'mAlex 2012-10-27
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

结构体用错了吧!先把书上基础知识看看
[/Quote]
我觉得你确实需要需要先把书上基础知识看看。
这里面涉及到的东西,全部都是对的。
最烦的就是你这种人,我猜你都不知道我说的啥
newtee 2012-10-25
  • 打赏
  • 举报
回复
结构体用错了吧!先把书上基础知识看看
I'mAlex 2012-10-25
  • 打赏
  • 举报
回复
难道,这里也涉及到左值和右值的问题?
I'mAlex 2012-10-25
  • 打赏
  • 举报
回复
问题1和问题2还是有区别的。
问题2中,实参和形参的传递,是一个值传递的过程,是一个值复制的过程。
问题1中,是怎么回事呢?
有点想不通

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧