Search code examples
c++carraysmultidimensional-arraycalloc

2d array, using calloc in C


I'm trying to create a 2D array of chars to storage lines of chars. For Example:

lines[0]="Hello";
lines[1]="Your Back";
lines[2]="Bye";

Since lines has to be dynamically cause i don't know how many lines i need at first. Here is the code i have:

int i;
char **lines= (char**) calloc(size, sizeof(char*));

for ( i = 0; i < size; i++ ){
lines[i] = (char*) calloc(200, sizeof(char));
}

for ( i = 0; i < size; i++ ){
free(lines[i]);
}

free(lines);

I know that each line can't go over 200 chars. I keep getting errors like "error C2059: syntax error : 'for'" and such. Any ideas of what i did wrong?


Solution

  • No the code is not in a function.

    You can't just put arbitrary statements outside of functions in C and C++. What you can do though is use a function to initialize the variable:

    char** init_lines() {
        char** ln = /* ... */;
        // your allocations etc. here
        return ln;
    }
    
    char** lines = init_lines();