Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array of strings

Tags:

c

string

pointers

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

like image 612
Kewley Avatar asked Jul 12 '10 02:07

Kewley


1 Answers

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.

like image 178
sth Avatar answered Oct 14 '22 13:10

sth