tags:

views:

132

answers:

3

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  A: 

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));
Maurizio Reginelli
+2  A: 
a = (int**)realloc(a, (n + 1) * sizeof(int *));
n++;
Tuomas Pelkonen
oh, thanks.. Size should be in bytes.
Sergey Gavruk
+2  A: 

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.
John Bode
+1 for the only correct answer (mentioning that `a = realloc(a, ...);` is wrong).
Alok