读书人

怎么给结构体成员赋值有关问题

发布时间: 2013-10-02 13:10:38 作者: rapoo

如何给结构体成员赋值问题
#include <stdio.h>

int main()
{
struct student{
char name[20];
int score;
};

struct student st={"John",100},*ptr;
// student st={"John",100},*ptr;
ptr=&st;

printf("ptr->name=%s\n",ptr->name);

return 0;
}

用gcc 4.2编译器无法编译:// student st={"John",100},*ptr;,但是用VS08却可以, 是不是编译器问题?
另外用gcc 4.2也无法这样编译:st={"John",100};是不是只能这样赋值:struct student st={"John",100};或者:st.name="John";st.score=100; ?
[解决办法]
C语言标准是需要struct student st带struct定义结构体变量的,student st的话并不是所有编译器都支持的,如果一定要用student st的话,那么最好用typedef进行定义:
typedef struct student{
char name[20];
int score;
}student;

引用:
#include <stdio.h>

int main()
{
struct student{
char name[20];
int score;
};

struct student st={"John",100},*ptr;
// student st={"John",100},*ptr;
ptr=&st;

printf("ptr->name=%s\n",ptr->name);

return 0;
}

用gcc 4.2编译器无法编译:// student st={"John",100},*ptr;,但是用VS08却可以, 是不是编译器问题?
另外用gcc 4.2也无法这样编译:st={"John",100};是不是只能这样赋值:struct student st={"John",100};或者:st.name="John";st.score=100; ?

[解决办法]
struct student st={"John",100};
只能在结构体定义的地方这样初始化;
如果在其他地方,就只能逐个成员初始化了,所以 st={"John",100}是不行的

读书人网 >C语言

热点推荐