Dynamically allocate user inputted string

后端 未结 4 1377
不思量自难忘°
不思量自难忘° 2020-12-04 02:47

I am trying to write a function that does the following things:

  • Start an input loop, printing \'> \' each iteration.
  • Take whatever the
4条回答
  •  一整个雨季
    2020-12-04 03:13

    No error checking, don't forget to free the pointer when you're done with it. If you use this code to read enormous lines, you deserve all the pain it will bring you.

    #include 
    #include 
    
    char *readInfiniteString() {
        int l = 256;
        char *buf = malloc(l);
        int p = 0;
        char ch;
    
        ch = getchar();
        while(ch != '\n') {
            buf[p++] = ch;
            if (p == l) {
                l += 256;
                buf = realloc(buf, l);
            }
            ch = getchar();
        }
        buf[p] = '\0';
    
        return buf;
    }
    
    int main(int argc, char *argv[]) {
        printf("> ");
        char *buf = readInfiniteString();
        printf("%s\n", buf);
        free(buf);
    }
    

提交回复
热议问题