c - 使用用户输入进行 malloc

标签 c malloc scanf

我正在尝试制作一个程序,用户输入一个字符串,然后如果他们想输入他们想要替换的字母以及用什么替换。我想使用 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);

最佳答案

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

一个例子是:

//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.
}

关于c - 使用用户输入进行 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22784524/

相关文章:

使用 c 编码 : warning: incompatible implicit declaration of built-in function ‘exp10’

我可以并且应该使用 CMake 进行设置吗

c - 在 C 中释放返回的变量

c++ - 读取/写入 void* 变量的单个字节

Char* 在不应该的时候显示 null

c - 为什么scanf必须取operator的地址

c - 增加存储在连续内存分配中的值

c - 如何在C while循环中仅打印 '\n'最后一个字符?

c - 为什么 malloc-ed 数组和非 malloced 数组的大小不同?

c - 如何使用 scanf() 将 n 个元素输入到数组中?