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

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

2013-10-02 
如何给结构体成员赋值问题#include stdio.hint main(){struct student{char name[20]int score}struc

如何给结构体成员赋值问题
#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}是不行的

热点排行
Bad Request.