Search code examples
arraysciochar

C char arrays for user input


I rarely log on and am very new to the C language, therefore I apologize if this is a duplicate question or if this is a silly query.

I'm currently learning C and am hitting a wall with strings. I understand that char arrays are used in place of strings in the language. My question is, is there a better way than to assign an arbitrary value when declaring a char[] for user input(i.e setting the size of the array to one value when the user might enter more or less than that amount of characters)?


Solution

  • If you're on a POSIX system (basically anything that's not Windows), you can use getline(3) to do this. It will automatically allocate a buffer of the right size for you. Otherwise, you'll have to guess a length, allocate that, then read the input up to that length, and if you guessed wrong, use realloc to increase your guess and try again.