tags:

views:

92

answers:

1

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

+8  A: 

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.

sth
I tried that originally and couldn't understand why it didn't work, but I did it without the brackets. Thanks alot!! :)
Kewley