0

我有以下问题。对于家庭作业,我应该为 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.

4

2 回答 2

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;
于 2013-01-29T22:58:43.487 回答
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;
}

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

于 2013-01-29T23:12:21.460 回答