How to use scanf to allocate memory and add to a variable.

Suppose the user enters a very long text and the predetermined size of the array truncates the string. I tried not to specify the size of the array and assign an empty string ("") , but strlen always returns 0, and if there are characters in str , then the length of the string.

Where is the problem?

 char str[] = ""; scanf("%s",str); printf ("Line size \"%s\" - %d characters\n", str, strlen (str) ); 
  • 2
    How are you going to change the size of an explicitly declared local str array ??? The size of the local array in C is rigidly fixed at the time of the announcement. - AnT

1 answer 1

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.