Search code examples
carrayspointersmultidimensional-arraydynamic-memory-allocation

Growing last row of an array implemented in array of pointer to arrays?


I have a dynamically-allocated two-dimensional data structure with capacity of 25 strings, each with a length up to 50. How can I grow the last row of t, an array of pointer to arrays, so it has room for a string of length 200 instead of 50? I want it to also preserve the contents of the string.

This is how I have dynamically allocated t, the two-dimensional array structure:

char **t;
t = (char **) malloc (25 * sizeof(char));

for (int i = 0; i < 25; i++)
  t[i] = (char *)malloc(50 * sizeof(char));

Can I access the last row with t[24]? How do I actually change the length of the string to 200 instead of 50?

So far, I have tried t[24] = (char *)malloc(200 * sizeof(char)); but I am not sure if this is correct.


Solution

  • Use realloc() to change the size of an existing allocation. If you use malloc() as you did, you lose the original contents of the array, and also lose the pointer to it so you can't free the memory.

    char *temp = realloc(t[24], 200 * sizeof(char));
    if (temp) {
        t[24] = temp;
    }