Sorry about missing an asterisk there:
mylife.friends=(char**)malloc(4*sizeof(char*));
As long as a pointer points to memory you own, you can use it:
const char* greeting = "Hello world!";
Valid, as the 'greeting' is pointing to an ASCIIZ array of characters stored in your program's memory space.
const char* crash = 12;
Invalid, as 'crash' is pointing to memory that does not belong to your program.
char* s80 = (char*)malloc( 80 );
Valid, as 's80' is pointing to memory that belongs to your program.
Remember now, that you want an array of strings. A string is an array of characters. So:
1 2 3 4 5 6 7 8
|
typedef char* string;
struct life
{
int years;
string* friends; // Points to one or more 'string's
string name; // A single 'string'
};
|
Now when you say
mylife.name = "Wilhelmina";
that works, simply because the
string (a pointer to one or more
chars) now points to the array of chars "Wilhelmina".
However, if you were to say
mylife.name[0] = 'A';
then you would have a problem, since 'name' points to some random place in memory (which probably doesn't belong to your program). The attempt to write to anything your program doesn't have rights to will segfault your program.
Before you can dereference any pointer, you must first point it to something you own:
1 2
|
mylife.name = "Jane";
printf( "%c\n", mylife.name[0] ); /* Works fine, since 'name' points to something you own */
|
It might be worth your time to read through the tutorials on
Compound Data Types
http://www.cplusplus.com/doc/tutorial/
Good luck!