簡體   English   中英

在C中更改2D動態數組的大小

[英]Change size of 2D dynamic array in C

我創建了一個2D動態數組:

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

然后我需要改變它的大小(添加新行):

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

但是當我想打印我的陣列時,

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");
    }
}

我有訪問權限違規。 打印第一行......我該怎么辦?

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

分配數組:

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
  }
}

調整數組大小:

/**
 * 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]);
}

注意事項:

  1. 從C89開始,您不必轉換malloc()calloc()realloc() ,這樣做可以抑制潛在有用的警告; 如果沒有別的,它使代碼更容易閱讀。
  2. 在對象上使用sizeof運算符,而不是類型; 它會稍微整理一下代碼,如果更改了a的類型,則不必返回並更新所有malloc / calloc / realloc調用。
  3. 如果數組中有n元素,則最后一個元素的索引將為n-1

在這段代碼中:

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

您正在訪問數組的第(n + 1)個位置。 你應該寫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM