Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change size of 2D dynamic array in C

Tags:

arrays

c

dynamic

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?

like image 226
Sergey Gavruk Avatar asked Mar 16 '10 19:03

Sergey Gavruk


3 Answers

a = (int**)realloc(a, (n + 1) * sizeof(int *));
n++;
like image 119
Tuomas Pelkonen Avatar answered Sep 30 '22 05:09

Tuomas Pelkonen


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.
like image 31
John Bode Avatar answered Sep 30 '22 07:09

John Bode


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));
like image 28
Maurizio Reginelli Avatar answered Sep 30 '22 06:09

Maurizio Reginelli