在C中为记录数组赋值

时间:2013-01-29 22:53:07

标签: c

我遇到了以下问题。对于家庭作业,我应该为5名学生创建一个记录“学生”的堆数组,然后分配一些值(名称等)。 现在,当我尝试按照之前的方式为记录分配值时,我得到一个“表达式预期{”错误。

Edit:

typedef struct student_t {
char hauptfach[128];
char name[64];
int matnr;
} student;

/Edit

student *students;
students = malloc(5*sizeof(student));


students[0] = {"Info", "Max Becker", 2781356};
students[1] = {"Soziologie", "Peter Hartz", 6666666};
students[2] = {"Hurensohnologie", "Huss Hodn", 0221567};
students[3] = {"Info", "Tomasz Kowalski", 73612723};
students[4] = {"Info", "Kevin Mueller", 712768329};

但是当我尝试分配单个值时,例如

students[0].hauptfach = "Informatik";

程序编译。

我做错了什么?

提前致谢,

d

2 个答案:

答案 0 :(得分:2)

您尚未显示结构定义,但我希望该字符串是char的数组,其大小最大。

要分配字符串,您需要使用strncpy。看看那个功能。

基本上,假设hauptfach成员的长度为MAX_LEN+1个字符:

strncpy( students[0].hauptfach, "Informatik", MAX_LEN+1 );
students[0].hauptfach[MAX_LEN] = 0;  // Force termination if string truncated.

哎呀,抱歉,我误解了你的问题。以上可能仍然适用。

你不能复制那样的结构。您必须在数组定义中初始化它:

struct mystruct students[5]  = {
  {"Info", "Max Becker", 2781356},
  {"Soziologie", "Peter Hartz", 6666666},
  {"Hurensohnologie", "Huss Hodn", 0221567},
  {"Info", "Tomasz Kowalski", 73612723},
  {"Info", "Kevin Mueller", 712768329}
};

或者您可以按照自己的方式单独指定字段。另一种选择是你可以替换一个完整的数组元素,比如初始化一个实例,然后像这样复制:

struct mystruct temp = {"Soziologie", "Peter Hartz", 6666666};
students[0] = temp;

答案 1 :(得分:1)

这两个陈述不能真正结合在一起:

1 students = malloc(5*sizeof(student));
2 students[0] = {"Info", "Max Becker", 2781356};

(1)表示您希望在运行时动态分配内存。

(2)表示您希望在编译时将列出的值分配给固定地址。不幸的是,编译器无法提前知道students[0]的地址是什么,所以它不能做你想要的。

我建议你创建一个辅助函数:

void initstudent(student *s, const char hf[], const char name[], int matnr){
  strncpy(s->hauptfach, hf, MAXLEN);
  strncpy(s->name, name, MAXLEN);
  s->matnr=matnr;
}

然后将其应用于每个学生。