You've allocated memory for three pointers, but you haven't allocated memory to store each string. Each stringArray[i]
needs to point to a buffer large enough to store the final string. That doesn't happen automatically in C, you have to make sure you've allocated memory to store the string itself.
For something like this, where you already know the number of strings and the maximum length of each string, you just need to allocate a 2D array of char
:
char stringArray[3][8]; // "string" plus 1 digit plus string terminator
for ( int i = 0; i < 3; i++ )
sprintf( stringArray[i], "string%d", i );
For a situation where you won't know the length of each string beforehand, you'll want to allocate the array of pointers like you do now, and then do a separate dynamic allocation when you know the length of each string:
char *stringArray[3];
for ( int i = 0; i < 3; i++ )
{
stringArray[i] = malloc( length_of_this_string() );
if ( stringArray[i] )
strcpy( stringArray[i], this_string );
}