开发者

Change size of 2D dynamic array in C

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, siz开发者_如何学Pythoneof(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?


a = (int**)realloc(a, (n + 1) * sizeof(int *));
n++;


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.


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜