Originally Posted by
Tripswitch
Can someone tell me if I've dynamically allocated 6 strings, and if this is right at all?
It looks close to correct. I suggest amending to:
Code:
#define NUM_STRINGS 6
int main(void)
{
char *str_array[NUM_STRINGS];
/* ... */
for (i = 0; i < NUM_STRINGS; i++)
{
if (scanf("%99s", array_i) == 1)
{
str_array[i] = malloc(strlen(array_i) + 1);
if (str_array[i])
{
strcpy(str_array[i], array_i);
}
else
{
/* Handle memory allocation failure */
}
}
else
{
/* Handle invalid input */
}
}
/* ... */
I used a named constant instead of 6: avoid magic numbers. I used "%99s" instead of "%s" for the format specification to avoid buffer overflow since array_i is an array of 100 characters. Admittedly, this does involve a magic number, so later you may wish to improve it.
For the malloc call, I removed the cast as it is unnecessary. I also removed the multiplication by sizeof(char) as sizeof(char) will always be equal to 1. If you prefer, you could write:
Code:
str_array[i] = malloc((strlen(array_i) + 1) * sizeof(str_array[i][0]));
Note the + 1: you should account for the null terminator.
Originally Posted by
Tripswitch
I'm confused because I've had to make a strcpy() statement to do it for all six, so does that not mean I now have 6 dynamically allocated strings AND 6 arrays of size 100 in memory?
Look at what you declared:
Code:
char *str_array[6];
char array_i[100];
This means that you have two arrays: one is an array of 6 pointers to char; the other is an array of 100 char. Later in your code, you use malloc to dynamically allocate storage for 6 arrays of char. Therefore, you end up with 2 arrays of fixed size and 6 dynamic arrays.
I see that you forgot to free what you malloc'ed.