首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

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

2012-11-16 
关于结构体变量赋初值和相同类型的结构体变量之间直接赋值的问题结构体:C/C++ codetypedef struct{char ma

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

C/C++ code
typedef struct{    char mark;    int score;    int id;}test_t;


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

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

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

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

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

test2 = test1; 
问题1.这里是对test2的赋初值,这样为什么就可以了呢?这里面涉及到了什么问题?
问题2.既然相同类型的结构体变量直接赋值操作,那么结构体变量就可以作为函数参数和返回值来使用了,作为参数传递时,将结构体整体赋给相同类型的形参,也算是对形参的赋初值了,这样为什么也可以呢?
其实,这俩是同一个问题。

[解决办法]
探讨

引用:

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

我觉得你确实需要需要先把书上基础知识看看。
这里面涉及到的东西,全部都是对的。
最烦的就是你这种人,我猜你都不知道我说的啥

[解决办法]
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.

热点排行