I've been trying to get this to work for a good few hours now, but I can't seem to get my head around it.
I'm trying to write a function that is able to return an array of strings.
#include <stdio.h>
#include <stdlib.h>
/**
* This is just a test, error checking ommited
*/
int FillArray( char *** Data );
int main()
{
char ** Data; //will hold the array
//build array
FillArray( &Data );
//output to test if it worked
printf( "%s\n", Data[0] );
printf( "%s\n", Data[1] );
return EXIT_SUCCESS;
}
int FillArray( char *** Data )
{
//allocate enough for 2 indices
*Data = malloc( sizeof(char*) * 2 );
//strings that will be stored
char * Hello = "hello\0";
char * Goodbye = "goodbye\0";
//fill the array
Data[0] = &Hello;
Data[1] = &Goodbye;
return EXIT_SUCCESS;
}
I'm probably getting mixed up with the pointers somewhere because I get the following output:
hello
Segmentation Fault
Yes, you got your pointer indirections mixed up, the members of the Data array should be set like this:
(*Data)[0] = Hello;
(*Data)[1] = Goodbye;
In the function, Data
points to an array, it is not an array itself.
Another note: You don't need to put explicit \0
characters in your string literals, they are null-terminated automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With