扫描输入到一个malloc指针不起作用

huangapple go评论65阅读模式
英文:

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 &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;



char *askFile()
{
    printf(&quot;Enter a file: &quot;);
    char *file = malloc(512 * sizeof(char));
    scanf(&quot;%s&quot;, file);

    return file;
}



int main()
{
    char *file = askFile();
    printf(&quot;%s&quot;, *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(&quot;%s&quot;, *file);

It was supposed to be:

printf(&quot;%s&quot;, 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(&quot;%s&quot;, *file); // Warning expected.

Save time. Enable all compiler warnings.

huangapple
  • 本文由 发表于 2023年1月9日 18:41:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定