5

I create a 2D dynamic array:

a = (int**)calloc(n-1, sizeof(int));
for(i = 0; i < (n-1); i++)
    a[i] = (int*)calloc(n, sizeof(int));

Then I need to change its size (add new line):

a = (int**)realloc(a, n);
a[n] = (int*)calloc(n, sizeof(int));

But when i want to print my array,

void Print(void){
    int i, j;
    for(i = 0; i < (n-1); i++){
        for(j = 0; j < n; j++){
            printf("%d\t", arr[i][j]);
        }
        printf("\n");
    }
}

i have access violation. First line is printed... What should I do?

1
  • OMG - this is badly broken before you even attempt the resize - you're assuming sizeof(int) == sizeof(int *) Commented Mar 16, 2010 at 20:00

3 Answers 3

4
a = (int**)realloc(a, (n + 1) * sizeof(int *));
n++;
Sign up to request clarification or add additional context in comments.

Comments

4

Allocating the array:

int **a;
ing **tmp;
size_t i;

a = calloc(n-1, sizeof *a);  // type of a==int **, type of *a==int *
if (a)
{
  for (i = 0; i < n-1; i++)
  {
    a[i] = calloc(n, sizeof *a[i]); // type of a[i]==int *, type of *a[i]==int
  }
}

Resizing the array:

/**
 * Assign result of realloc to a temporary variable; if realloc fails it will
 * return NULL, which would cause us to lose our pointer in the event of 
 * a failure.
 */
tmp = realloc(a, sizeof *a * n);
if (!tmp)
{
  // realloc failed; handle error or exit
}
else
{
  a = tmp;
  a[n-1] = calloc(n, sizeof *a[n-1]);
}

Things to note:

  1. As of C89, you do not have to cast the result of malloc(), calloc(), or realloc(), and doing so can suppress a potentially useful warning; if nothing else, it makes the code easier to read.
  2. Use the sizeof operator on the object, not the type; it unclutters the code a little bit, and you don't have to go back and update all your malloc/calloc/realloc calls if you change the type of a.
  3. If you have n elements in the array, the index of the last element will be n-1.

1 Comment

+1 for the only correct answer (mentioning that a = realloc(a, ...); is wrong).
1

In this code:

a = (int**)realloc(a, n);
a[n] = (int*)calloc(n, sizeof(int));

you are accessing the (n+1)th position of the array. You should write:

a = (int**)realloc(a, n * sizeof(int*));
a[n-1] = (int*)calloc(n, sizeof(int));

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.