I'm new to C and I'm currently working on a project that I need to read a list from a Json file (using json-c library). So, I created a function that returns an array of string (the list). I searched and I found out that to return array of string in a function you need to type something like:
char** readJson(...) {
...
}
and in the main:
int main() {
...
char** list = readJson();
...
}
My problem is that when I create my array, in the read function, I don't declare it, I loop through the list items (from the json object) and I add the them in the list. For example, I don't:
char** list = {"...", "..."}
I do:
char** list;
for (int i = 0; i < LIST_SIZE; i++) {
strcpy(list[i], json_object_get_string(json_obj));
}
And when I try to print the list item after strcpy (in for loop) it closes the program. So, I tried to create the array like that:
char list[LIST_SIZE][MAX_CHAR];
And then return this:
char** final = list;
return final;
And it worked. But, when I am returning the list it gives me a warning in the compiler:
main.c:66:20: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
And when I try to print the list in main it crashes.
Here is the source code. Check it if you want.
Please, help me.
As mentioned in the comments, you cannot simply interchange arrays and pointers. Based on your use-case, I would suggest using malloc()
to dynamically allocate your list
variable. Something along the lines of:
char **list = malloc(LIST_SIZE * sizeof(char *));
for(int i = 0; i < LIST_SIZE; i++)
list[i] = malloc(MAX_CHAR * sizeof(char));
Doing so will still allow you to reference specific words/sentences by using list[i]
and you can return list
as a char **
:
char **result = list;
return result;