0

I have a C code like below:

char* text;
get(text); //or
scanf("%s",text);

But I try to run this it breaks. Because I did not give size for text.
Why I did not give a size for text, 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?

namco
  • 6,208
  • 20
  • 59
  • 83

1 Answers1

10

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);  
    free(s);
    return 0;
}  

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

haccks
  • 104,019
  • 25
  • 176
  • 264
  • Doesn't it depend on the architecture for the size of char? You have used malloc(1) instead of malloc(sizeof(char)). – Kumar Oct 17 '21 at 12:32
  • @Kumar; If I remember, size of char is always `1` byte (though a byte is not necessarily of 8 bit on every architecture). – haccks Oct 17 '21 at 21:22