I want to read a set of strings in an array. The size of the array is to be decided at run-time using malloc or alloc i.e. the number of strings are accepted as input. I tried the following code but it doesn’t worked.
char *array;
array=(char*)malloc(sizeof(char)*t); //t is the size of array
for(int temp=0;temp<t;temp++)
{
gets(a[temp]);
}
The same worked in case of array of integers.
Please help me in finding the solution.
C doesn’t have any automatic built-in support for storing strings, there is no variable that is “a string”, and can automatically grow to hold the proper number of characters. You need to allocate the memory yourself.
What you’re doing now, is allocating place for the proper number of character pointers, but not for any characters. So the
gets()call is writing into memory that is not allocated, which is undefined behavior. Since the integers fit completely in a single allocation each, that’s why similar code worked for integers. Strings are more complex, so you need to do more work.If there is any known upper bound on the length of these strings, you can use a temporary buffer of fixed length, and then copy from that into newly allocated dynamic memory once you know the required size. If there is no such bound, you need to repeat the same concept, by reading a fixed block, storing that, and if no end of line was found, read another block, grow the memory allocation for this string using
realloc(), append the new characters, and repeat until the line ends.As a side note, you should always avoid using
gets(), since it doesn’t support protecting your program against buffer overrun. It’s much better to use fgets(), documented on the same page.