英文:
Scanning input into a malloc pointer not working
问题
我有这段代码,但它不起作用。无论我输入什么都不打印。
#include <stdio.h>
#include <stdlib.h>
char *askFile()
{
printf("Enter a file: ");
char *file = malloc(512 * sizeof(char));
scanf("%s", file);
return file;
}
int main()
{
char *file = askFile();
printf("%s", *file);
return 0;
}
为什么它不工作?
英文:
I have this code but it's not working. No matter what I type it prints nothing.
#include <stdio.h>
#include <stdlib.h>
char *askFile()
{
printf("Enter a file: ");
char *file = malloc(512 * sizeof(char));
scanf("%s", file);
return file;
}
int main()
{
char *file = askFile();
printf("%s", *file);
return 0;
}
Why doesn't it work?
答案1
得分: 2
如@Someprogrammerdude在评论中所说,错误是:
printf("%s", *file);
应该改为:
printf("%s", file);
因为*file指向第一个元素。
英文:
As @Someprogrammerdude said in the comments the mistake was:
printf("%s", *file);
It was supposed to be:
printf("%s", file);
Since *file points to the first element.
答案2
得分: 0
关键错误是没有使用一个具有所有警告启用的优秀编译器。一个良好启用的编译器本应警告关于格式说明符和类型不匹配的问题。
char *file = ...;
printf("%s", *file); // 预期警告。
节省时间。启用所有编译器警告。
英文:
The key mistake is not using a good compiler with all warnings enabled. A good well-enabled compiler would have warned about the specifier-type mismatch.
char *file =...;
printf("%s", *file); // Warning expected.
Save time. Enable all compiler warnings.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论