【问题标题】:malloc with user inputmalloc 与用户输入
【发布时间】:2014-04-01 11:28:24
【问题描述】:

我正在尝试制作一个用户输入字符串的程序,然后如果他们想输入他们想要替换的字母以及用什么替换。我想使用 malloc 来设置数组,但是我该如何使用 scanf 呢?

请有人帮忙。

谢谢!

这是程序在进入替换方法之前的样子:

char *s,x,y;

printf("Please enter String \n");
scanf("%s ", malloc(s));

printf("Please enter the character you want to replace\n");
scanf("%c ", &x); 

printf("Please enter replacment \n");
scanf("%c ", &y);

prinf("%s",s);

【问题讨论】:

  • 我认为你想要 POSIX getline()(不是 C99 标准的一部分)。
  • 您对 malloc 的使用是非常错误的: Malloc 获取字节数并返回一个指针。你传给它一个指针。

标签: c malloc scanf


【解决方案1】:

您无法事先知道用户输入的大小,因此如果用户输入尚未结束,则需要动态分配更多内存。

一个例子是:

//don't forget to free() the result when done!
char *read_with_alloc(FILE *f) {
    size_t bufsize = 8;
    char *buf = (char *) malloc(bufsize);
    size_t pos = 0;

    while (1) {
        int c = fgetc(f);

        //read until EOF, 0 or newline is read
        if (c < 0 or c == '\0' or c == '\n') {
            buf[pos] = '\0';
            return buf;
        }

        buf[pos++] = (char) c;

        //enlarge buf to hold whole string
        if (pos == bufsize) {
            bufsize *= 2;
            buf = (char *) realloc((void *) buf, bufsize);
        }
    }
}

一个实用的替代解决方案是限制 buf 大小(例如,256 个字符),并确保只读取该数量的字节:

char buf[256]; //alternative: char *buf = malloc(256), make sure you understand the precise difference between these two!
if (scanf("%255s", buf) != 1) {
   //something went wrong! your error handling here.
}

【讨论】:

    【解决方案2】:
    scanf("%s ", malloc(s));
    

    这是什么意思? s uninitialized 是指针,它可以有任何值,比如0x54654,它是未定义的行为。

    你的代码应该是,

    int size_of_intput = 100; //decide size of string
    s = malloc(size_of_intput);
    scanf("%s ", s);
    

    【讨论】:

    • 您应该始终确保不会导致缓冲区溢出。 >= 100 个字符的用户输入很可能会导致代码堆损坏!改为传递scanf("%99s ", s),并检查scanf的返回值。
    • @mic_e 很好的建议。不知道%99s 可能。
    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多