while declaring arrays we have to mention size of arrays as arrays cannot be dynamic similarly string is array of chars how can we not mention size of array we simply use Getstring() or scanf
1 Answer
Good question! GetString
uses a slightly different technique, namely dynamic memory allocation. Using dynamic memory allocation, you can allocate and/or free memory at run time (i.e., as the program is running). You'll get exposed to that technique as you proceed with the course.
For now, what you should probably know is that basically GetString
allocates a chunk of memory, reads the string that the user enters character by character, stores the current character at the appropriate location and, if at some point there's not enough space left in the array, it reallocates a new array with ~double the size of the older one, copies the contents of the older array into the newer array, frees the older array and the process repeats. If all goes well, GetString
then terminates the string and returns it for you.
The string returned by GetString
lives in a location in memory called the heap. The data within the variables that we create inside our functions typically live in a location in memory known as the stack.
Unlike data that lives on the stack, data that lives on the heap are typically referred to as long-term data (i.e., they never go away until we free the memory manually).
Feel free to take a look at the source code for GetString
! It may be also useful to watch the short on the CS50 library!