【发布时间】:2018-04-27 15:23:37
【问题描述】:
这是我的完整代码,它看起来可以工作,但效果不是很好。 我会接受任何像这样工作的代码。
首先,代码可以工作,但是当我想将第三个名称添加到结构时,它会崩溃。
还有其他方法吗?
我需要结构,因为将来我想添加一些其他参数,比如年龄、平均、性别等。
请帮帮我。
//The student table
typedef struct students {
char name[50];
} students;
//Global params
int scount = 0;
students *s;
//Basic functions
void addNewStudent();
int main()
{
int loop = 1;
char in;
int ch;
printf("Willkommen.\n Wahlen Sie bitte von die folgenden Optionen:\n");
while (loop)
{
printf("\t[1] Neue Student eingeben\n");
printf("\t[9] Programm beenden\n");
scanf(" %c", &in);
while ((ch = getchar()) != '\n');
switch (in)
{
case '1':
addNewStudent();
break;
case '9':
loop = 0;
break;
default: printf("------\nOption nicht gefunden.\n------\n");
break;
}
}
free(s);
return 0;
}
void addNewStudent()
{
int index = 0;
if (scount == 0)
{
s = (students*)malloc(sizeof(students));
}
else
{
realloc(s, sizeof(students) * scount);
}
printf("Geben Sie Bitte die Name:\n");
fgets(s[scount].name, sizeof(s[scount].name), stdin);
while (s[scount].name[index] != '\n')
{
index++;
}
s[scount].name[index] = '\0';
scount++;
}
我正在使用 Visual Studio。
感谢您的帮助!
【问题讨论】:
-
建议将结构名称更改为单数,即学生或学生
-
Don't cast
malloc:s = malloc(sizeof(students)); -
@lurker: 更好的是
s = malloc(sizeof *s);- 防止更改指向的类型。 -
没有 stdlib.h 包含,因此如果您通过恐龙 C90 编译器运行此代码,确实可能会崩溃和烧毁。
-
realloc(s, sizeof(students) * scount);-->s = realloc(s, sizeof *s * (scount + 1)); if (s== NULL) OutOfMemory();
标签: c pointers struct malloc realloc