0

I have a two-dimensional int array allocated as follows:

int **matrix = (int**)malloc(x * sizeof(int));
for (i = 0; i < x; i++)
    matrix[i] = (int*)malloc(y * sizeof(int));

If I do realloc this array by the following code

int **matrix = (int**)realloc(matrix, x * sizeof(int));
for (i = 0; i < x; i++)
    matrix[i] = (int*)malloc((y) * sizeof(int));

will there be any leftover "tails" of second dimension of the array and should I use free() function for them before reallocating, or they will go away themselves?

12
  • There is no 2D array, nor something that can be used as one. A pointer is not an array! Commented Mar 19, 2016 at 21:18
  • x*sizeof(int) --> x*sizeof(int*) Commented Mar 19, 2016 at 21:21
  • Some of your sizeof expressions are wrong. When allocating/reallocating matrix, you need x*sizeof(int *). Commented Mar 19, 2016 at 21:22
  • 2
    Also, do not cast the return value of malloc Commented Mar 19, 2016 at 21:22
  • Well I can access elements of this "array" by using indexes as always (array[i][j]) and easily passing it to other functions. That is the only things I need for now. Edit: Thanks Weather Vane Commented Mar 19, 2016 at 21:22

2 Answers 2

1

You will completely lose data in your matrix, so this is not really reallocing anything; you could just as well free and malloc the top-level array, getting possibly better performance. Furthermore your code would leak memory, because the 2nd level allocations are not freed.

Sign up to request clarification or add additional context in comments.

1 Comment

As I suspected. Thanks!
1

Here is how you can resize the 2D matrix while keeping the current values intact, initializing the newly allocated cells to 0 and freeing any extra leftovers:

// matrix was allocated to x and y
// reallocate it to newx, newy
for (i = newx; i < x; i++) { /* free unneeded rows */
    free(matrix[i]);
}
matrix = realloc(matrix, sizeof(*matrix) * newx);
for (i = x; i < newx; i++) { /* initialize the new row pointers */
    matrix[i] = NULL;
}
for (i = 0; i < newx; i++) {
    matrix[i] = realloc(matrix[i], sizeof(*matrix[i]) * newy);
    for (int j = y; j < newy; j++)
        matrix[i][j] = 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.