5

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

3
  • 2
    You don't need \0 at the end of a string. When you use the double quotes, the compiler adds the \0 character for you. You only need the \0 if you declare your strings like char Hello[] = { 'h', 'e', 'l', 'l', 'o', '\0' }; Commented Jul 12, 2010 at 2:34
  • 1
    I know I'm being a nuisance but please free that which you have malloc'd. It is good practise and if you always do it as you write code you'll forget less often. Commented Jul 12, 2010 at 2:39
  • I knew I didn't need the null terminator but included it for some reason, thanks for pointing that out. Thanks Dan, I usually do, but this was just a test. Thanks. Commented Jul 12, 2010 at 11:45

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.