[英]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]);
}
注意事項:
malloc()
, calloc()
或realloc()
,這樣做可以抑制潛在有用的警告; 如果沒有別的,它使代碼更容易閱讀。 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.