我正在实现一个程序,该程序从标准输入或文件中读取学生 ID 和姓名,并使它们按姓名排序并按编号排序。有趣的是我不明白为什么但 scanf 不起作用。这是我使用 scanf 时的代码:
int n=0;
while(n<SIZE){
scanf("%d %s\n",&std_array[n].id, std_array[n].name);
n++;
}
for(int i=0; i<SIZE; i++)
printf("%d %s\n",std_array[i].id,std_array[i].name);
这是我的结构:
struct Student {
char *name;
int id;};
当我从文件中读取并打印它们时,输出是:
> 12586546 (null) 0 (null) 0 (null) 0 (null) 0 (null) 0 (null) 0 (null)
> 0 (null) 0 (null) 0 (null)
虽然文件有一些数字和名称,例如 21456764 john 45797654 fred 等,但它没有成功读取。
注意:我知道我们像你们建议的那样修复结构的方法,但我必须学习使用 char 指针来执行此操作的方法...
最佳答案
执行此操作时:
struct Student {
char *name; // This does not allocate memory
int id;};
这里,name是一个指针,没有分配内存,表现得像一个未初始化的文字字符串。
尝试修改它会产生未定义的行为。
替换为:
struct Student {
char name[50];
int id;};
或
struct Student {
char name[] = "Initial value gives maximum length. Do not write more!";
int id;};
关于c - scanf 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720037/