當我編譯該代碼時,我得到「未聲明的標識符數據的使用」。正如你可以看到的問題是,add_student函數不能「看到」學生數組。在函數中使用未聲明的標識符
該怎麼做才能正常工作?
#include <stdio.h>
typedef struct {
char *name;
int age;
char *sex;
int class;
}student;
void add_student(int, char*, int, char*, int);
int main (int argc, const char * argv[])
{
student data[5];
add_student(5, "Mery", 3, "female", 8);
return 0;
}
void add_student(int sequence, char *name, int age, char *sex, int class) {
strcpy(data[sequence].name, name);
data[sequence].age[13];
strcpy(data[sequence].sex, sex);
data[sequence].class[2];
}
我已修復所有錯誤。謝謝 ! – summerc 2012-01-05 18:08:19
有沒有一種更優雅的方式來分配名字和性別的記憶。這裏我是怎麼做的(對不起,但沒有找到格式化代碼的方法) data [sequence] .name = malloc(strlen(name)+ 1); < strcpy(data [sequence] .name,name); data [sequence] .age = age; data [sequence] .sex = malloc(strlen(sex)+ 1); strcpy(data [sequence] .sex,sex); data [sequence] .class = class; – summerc 2012-01-05 18:09:42
@ user1074077:不,'malloc()'很好。還有'strdup()'。無論哪種情況,別忘了'free()'! – NPE 2012-01-05 18:11:16