带有用户输入的malloc

带有用户输入的malloc,c,malloc,scanf,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 ", &

我试图制作一个程序,用户输入一个字符串,然后如果他们想输入一个字母,他们想替换什么。我想使用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);
这是什么意思?s uninitialized是指针,它可以有任何值,比如说
0x54654
,它是未定义的行为

你的代码应该是

int size_of_intput = 100; //decide size of string
s = malloc(size_of_intput);
scanf("%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);
        }
    }
}

我认为您需要POSIX(不是C99标准的一部分),您对malloc的使用是非常错误的:malloc获取字节数并返回指针。你给它一个指针。你应该始终确保没有造成缓冲区溢出。大于等于100个字符的用户输入很可能会导致代码堆损坏!改为传递
scanf(“%99s”,s)
,并检查scanf的返回值。@mic\u这是一个很好的建议。可能不知道
%99s
//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);
        }
    }
}
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.
}