我创建了一个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");
}
}
我有访问权限违规。打印第一行...... 我该怎么办?
答案 0 :(得分:4)
a = (int**)realloc(a, (n + 1) * sizeof(int *));
n++;
答案 1 :(得分:4)
分配数组:
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
。 答案 2 :(得分: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));