char *result[1];
C does not automatically allocate space to store a string's contents - you have to do that yourself. In this case you've only allocated enough space to store a pointer value (i.e., an address)1. Since it's declared without an initializer, that pointer value is indeterminate - it could be 0
, it could be 0xdeadbeef
, it could be any other value. In this case, that indeterminate pointer value just happens to point to memory that's writable, so the operation succeeds.
But...
Since it was not obtained by using the &
operator on an object during that object's lifetime or through a malloc
, calloc
, or realloc
call, that pointer value is invalid and the behavior on attempting to write through an invalid pointer is undefined. Unfortunately, one of the symptoms of undefined behavior is working as expected - as long as you don't clobber anything "important" your code will appear to function correctly.
char *result[2];
Same deal as above, although this time one or both of the indeterminate pointer values points to memory that is not writable, hence the runtime error.
Strings (including string literals) are ultimately stored in arrays of character type, so you'll have to allocate arrays that are long enough to store the entire string plus the terminator. "String 1"
is 8 characters long, so you need to allocate an array that's at least 9 characters wide to store the string plus the terminator:
char result[9];
strcpy( result, "String 1" );
or if your implementation supports variable-length arrays2, you can do:
size_t len = strlen( "String 1" );
char result[len + 1];
strcpy( result, "String 1" );
or if you want to allocate memory dynamically:
size_t len = strlen( "String 1" );
char *result = malloc( len + 1 );
if ( result )
strcpy( result, "String 1" );
If you want an array of strings, you'll have to use a 2D array of char:
char result[2][9];
strcpy( result[0], "String 1" );
strcpy( result[1], "String 2" );
or an array of pointers to char
that point to other arrays or dynamic memory:
char *result[2];
result[0] = malloc( strlen( "String 1" ) + 1 );
result[1] = malloc( strlen( "String 2" ) + 1 );
if ( result[0] )
strcpy( result[0], "String 1" );
if ( result[1] )
strcpy( result[1], "String 2" );
- Arrays are not pointers and pointers are not arrays. Array expressions "decay" to pointer expressions as necessary, but they are ultimately two different animals.
- Despite their name, variable-length arrays are not resizable - their size is fixed for the duration of their lifetimes. "Variable" refers to the fact that their size can change from definition to definition.