Chinaunix

标题: 《The C Programming language》结构体赋值的问题? [打印本页]

作者: xiaowh00    时间: 2012-06-26 09:49
标题: 《The C Programming language》结构体赋值的问题?
#include <stdio.h>

main()
{
        struct point
        {
                int x;
                int y;
        };
       
        struct point x1;

        x1={320,200};
       
        printf("%d %d\n",x1.y,x1.x);
}
gcc 编译后提示:
6.1.c: In function ‘main’:
6.1.c:13: error: expected expression before ‘{’ token

而用x1.x=320;x1.y=200赋值就正常
书《The C Programming language》上说: A structure can be initialized by following its definition with a list of initializers, each a constant expression, for the members:
   struct maxpt = { 320, 200 };
求指导?


作者: joatsikuy    时间: 2012-06-26 10:03
回复 1# xiaowh00

struct point x1;

        x1={320,200};
这不是初始化,而是赋值。

这种写法叫initialized struct point x1 = {320,200};


   
作者: changzhiwin    时间: 2012-06-26 10:04
  1. #include <stdio.h>
  2. int main()
  3. {
  4.         struct test{
  5.                 int x,y;
  6.         };

  7.         struct test t = {20, 12};
  8.         printf("%d %d\n", t.x, t.y);

  9.         return 0;
  10. }
复制代码
is ok, you should notice "following its definition"
作者: xdsupermanli    时间: 2012-06-26 10:05
楼上正解!
作者: xiaowh00    时间: 2012-06-26 10:07
恩,谢谢你的点播,瞬间貌似懂了

#include <stdio.h>

main()
{
        struct point
        {
                int x;
                int y;
        };
       
        struct point x1={200,500};


        printf("%d,%d\n",x1.y,x1.x);
}  这样貌似就可以了

回复 2# joatsikuy


   
作者: xiaowh00    时间: 2012-06-26 10:10
本帖最后由 xiaowh00 于 2012-06-26 10:10 编辑

那么是不是说结构体只能初始化,或者单独给某些成员赋值,而不能整体赋值呢,我刚学C语言的,很多不懂回复 2# joatsikuy


   
作者: zooyo    时间: 2012-06-26 10:34
提示: 作者被禁止或删除 内容自动屏蔽
作者: zooyo    时间: 2012-06-26 10:35
提示: 作者被禁止或删除 内容自动屏蔽
作者: xdsupermanli    时间: 2012-06-26 10:55
要搞清楚变量初始化和赋值的区别。变量在定义时就进行赋值叫做初始化;变量定义完后,在之后的语句进行赋值,这个叫赋值。
作者: xiaowh00    时间: 2012-06-26 11:14
那么是不是说结构体只能初始化,或者单独给某些成员赋值,而不能整体赋值呢?回复 9# xdsupermanli


   
作者: xdsupermanli    时间: 2012-06-26 11:19
是的。回复 10# xiaowh00


   
作者: pmerofc    时间: 2012-06-26 18:53
提示: 作者被禁止或删除 内容自动屏蔽
作者: xiaowh00    时间: 2012-06-27 10:42
试过了,这个真可以,请问这个用法什么意思呢? 还是就是这么规定的回复 12# pmerofc


   
作者: pmerofc    时间: 2012-06-27 17:40
提示: 作者被禁止或删除 内容自动屏蔽
作者: lilinly225    时间: 2012-06-27 22:55
哈哈,   差点没雷到

面向对象了,这不直接
作者: lilinly225    时间: 2012-06-27 22:56
struct point x1;
x1={320,200};
这是赋值,C好像不支持这样赋值吧,

如果初始化的话,那么就应该可以的

不懂C的飘过
作者: Moon_Bird    时间: 2012-07-17 23:03
本帖最后由 Moon_Bird 于 2012-07-17 23:40 编辑
pmerofc 发表于 2012-06-27 17:40
回复 13# xiaowh00

第一次见到这种用法...............  那么数组也可以以这种方式赋值罗 ?
作者: pmerofc    时间: 2012-07-18 09:45
提示: 作者被禁止或删除 内容自动屏蔽
作者: yizhengming    时间: 2012-12-13 22:01
学习了....
作者: captivated    时间: 2012-12-14 23:15
回复 14# pmerofc


    这个不错, 表示学习了




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2