Hi all,
how do i use malloc to allocate memory for an array of strings?
can i write the code like this?
Code:char *line = (char *)malloc(sizeof(char) * 100 * 100); line[0] = "how"; line[1] = "are"; line[2] = "you"; ...
Thanks...
Hi all,
how do i use malloc to allocate memory for an array of strings?
can i write the code like this?
Code:char *line = (char *)malloc(sizeof(char) * 100 * 100); line[0] = "how"; line[1] = "are"; line[2] = "you"; ...
Thanks...
First of all, typecasting the return value of malloc() is unnecessary. Secondly, you'll want line to be a pointer to a pointer of type char. Then you set line equal to enough allocated memory to hold the number of strings you want multiplied by the size of a pointer.
If you understand what you're doing, you're not learning anything.
If you want a hundred strings, then you need a hundred pointers. So you allocated that many pointers. Then you go through and loop and allocated space for each string.
Quzah.
Hope is the first step on the road to disappointment.
Your method will not produce the results you are wanting.
Essentially here is what you now have in memory.
Line []=
howareyou......................................... ...........->((100x100)-9 bytes)
Of course "how are you" would be in hex but you get the point. There is a way to properly store all strings in one huge linear array rather than using multiple indirection or a 2D array.
Write a function that will append the null terminator to the end of a string. Put this string into array at the correct offset.
Note that by doing this you will still run into trouble using the C library of functions for manipulating strings. Those functions will only test this string: "how" since the null terminator would be at the end of how. Also printf() would only print "how".