c - scanf 不起作用

标签 c pointers scanf dynamic-memory-allocation

我正在实现一个程序,该程序从标准输入或文件中读取学生 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/

相关文章:

c - "Gestalt"有什么作用?

C++如何在不复制的情况下将元素存储在双端队列中

c - 读取 fscanf 上的空间

c - 如何使用 strtok 打印二进制数?

c - 传递错误类型参数时函数的奇怪行为

c - 在C中复制字符串(包括内存分配、指针等)

c - 编译内核模块源代码时如何包含标准头文件?

复杂声明

c - 为什么将指向字符串的指针传递给函数时是 2 星

c - 忽略尾部读取大小受限的输入行