namco namco - 1 year ago 84
C Question

How to get char* with unknown length in C?

I have a C code like below:

char* text;
get(text); //or

But I try to run this it breaks. Because I did not give size for

Why I did not give a size for
, because i don't know what is the size of
text that user is going to enter.
So, what can i do, in situations like this?
How can I read the text if I don't know the length of string?

Answer Source

You can try this

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
    char *s = malloc(1);
    printf("Enter a string: \t"); // It can be of any length
    int c;
    int i = 0;
    /* Read characters until found an EOF or newline character. */
    while((c = getchar()) != '\n' && c != EOF)
        s[i++] = c;
        s = realloc(s, i+1); // Add space for another character to be read.
    s[i] = '\0';  // Null terminate the string
    printf("Entered string: \t%s\n", s);  
    return 0;

Note: Never use gets function to read a string. Its no longer exist in standard C.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download