Returned string array

I tried to get this to work for several hours, but it seems like I can't think of it.

I am trying to write a function that can 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 am probably confused with pointers somewhere because I get the following output:

hi
segmentation error

+5
source share
1 answer

Yes, you have lost pointer offsets, the members of the Data array should be set as follows:

(*Data)[0] = Hello;
(*Data)[1] = Goodbye;

The function Datapoints to an array, this is not the array itself.

Another note: you do not need to put explicit characters \0in your string literals, they automatically terminate to zero.

+10
source

All Articles