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?
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:
malloc()
, calloc()
, or realloc()
, and doing so can suppress a potentially useful warning; if nothing else, it makes the code easier to read.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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With