Announcement
char str[] = "";
equivalent to ad
char str[1] = "";
The array gets a size of 1, which after that will never change again. It is impossible to place a string in such an array, except an empty one.
In any case, a local or static array in the C language gets a specific fixed size at the definition point. Change this size later is no longer possible. Therefore, to solve the problem of reading a string of unknown length using an explicit array declaration will not work.
The array size will have to be changed as needed, i.e. "on the fly". And only the size of a dynamically allocated (through malloc ) array can change on the fly. However, even in this case, there is no ready-made solution in the standard scanf . For reading lines of unknown, unlimited length in advance, it is better to use not scanf , but a cyclic call to fgets with a periodic realloc dynamic buffer, until the entire line is read.
However, GNU scanf supports a non-standard modifier m that implements the required functionality. This modifier works with the s and [] formats:
char *str = NULL; scanf("%ms", &str); ... free(str);
Please note that in this case, a pointer to a pointer should be sent to scanf , i.e. char ** argument.
Earlier in this role was the modifier a . However, starting with C99, the character a "busy" under one of the standard formats. So if you want to take advantage of this opportunity, be careful with the version of the library.
strarray ??? The size of the local array in C is rigidly fixed at the time of the announcement. - AnT