I have 2D char array, dynamically allocated (using malloc). I need to add another line to it but I have no idea how to use realloc with 2D arrays.
I have this:

res = (char **) malloc(1 * sizeof (char*));
for (i = 0; i < 1; i++) {
    res[i] = (char *) malloc(z * sizeof (char));
        }

1xz array (one line with z elements)
Now I need to change it to 2xz.

res=(char **) realloc(res, sizeof(*res)*count);
for(k=0;k<count;k++) res[k]=(char *) realloc(res[i],sizeof(*res[i])*z);
for(k=pocet;k<count+1;k++) res[k]=(char *) malloc(sizeof(*res[i])*z);

I was told to reallocate what was already allocated using realloc and then allocate new part using malloc. But it's not working and program crashes. Can anyone give me a hint? :)

You only need to realloc the first dimension, then malloc the newly added pointers. In this case only one new pointer is being appended to the "array", so it could be as simple as this:

res = realloc(res, sizeof(*res) * count);
res[count - 1] = malloc(z);

<insert caveats about realloc and testing allocations for failure>

Ok now I have this

res = (char**) realloc(res, sizeof(*res) * count);
res[count- 1] =(char*) malloc(z*sizeof(char));

and it's still not working.
I need (char**) because the malloc and realloc returns void right? (I tried with and without it, none works)

I tried to add some printf lines and the problem seems to be in the second line of the code.

>and it's still not working.
Useless information.

>I need (char**) because the malloc and realloc returns void right?
It's not needed in C. That conversion is implicit.

>I tried with and without it, none works
Then you're compiling as C++.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.