1

I want to initialize an array of strings in C through a function. I used this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void createArrayStrings(char ** listStr){
    listStr = malloc (3 * sizeof(char*));
    listStr[0] = malloc(2 * sizeof(char)); // N chars + '\0'
    listStr[1] = malloc(3 * sizeof(char));
    listStr[2] = malloc(4 * sizeof(char));
    strcpy(listStr[0], "A");
    strcpy(listStr[1], "AB");
    strcpy(listStr[2], "ABC");
}

int main(int argc, const char * argv[]) {
    char ** listStr = NULL;
    createArrayStrings(listStr);
    for (int i = 0;i<3;i++){
        printf("%s\n",listStr[i]);
    }
    return 0;
}

But there is an execution error EXEC_BAD_ACCESS in printf. Where is my error? Thanks.

0

1 Answer 1

1

You cannot use the variable listStr in main, because it is never filled with an actual value. When you call createArrayStrings, the argument you are passing is copied by value - which means that you have a NEW copy in the new function. The copy now is filled with the data you need, but not the original variable in main (it is still null).

The best way is to let createArrayStrings return the value of listStr, and assign it to listStr in your main function:

char ** listStr = createArrayStrings();

And the new create function would look like this:

void createArrayStrings(){
    char ** listStr = malloc (3 * sizeof(char*));
    ...
    return listStr;
}
Sign up to request clarification or add additional context in comments.

7 Comments

Alternatively the function can take a pointer to the array of strings pointer, that is, a char ***.
Yes, this would the usual answer on stack overflow (by my experience). But why give OP a solution that is in general discarded? You should avoid output prameters in functions as long as you can. To me it's much better to return it.
Thanks. However, how should I proceed if I need to initialize two different arrays of strings within the same function? I guess it is by using char ***.
Do you have to do the whole initialization in the same function? I think it's much more convenient to have one function that creates one array of strings. And as soon as you need a second array, you just call the function again and assign it to another variable.
I was just pointing out an alternative. I agree that returning char** in this case is ideal.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.