【问题标题】:Scanning input into a malloc pointer not working将输入扫描到 malloc 指针中不起作用
【发布时间】:2023-01-09 18:52:18
【问题描述】:

我有这段代码,但它不起作用。无论我输入什么,它都不会打印任何内容。

#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;
}

为什么它不起作用?

【问题讨论】:

  • *file 与 file[0] 相同。它是字符串中的第一个字符。
  • @Someprogrammerdude 糟糕,抱歉,我忘记了那个 C 特性。谢谢。

标签: c input


【解决方案1】:

正如@Someprogrammerdude 在 cmets 中所说的那样,错误是:

printf("%s", *file);

它应该是:

printf("%s", file);

因为 *file 指向第一个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多