I have a 2D dynamic array.
I enter a line of 0’s after line which has a biggest number:
void InsertZero(int **a, int pos){
int i, j;
a = (int**)realloc(a, n * sizeof(*a));
a[n-1] = (int*)calloc(n, sizeof(**a));
d = 0;
for(i = n-1; i > pos; i--){
for(j = 0; j < n; j++){
a[i][j] = a[i-1][j];
printf("%d ", a[i][j]);
}
}
for(i = 0; i < n; i++){
a[pos][i] = 0;
}
}
If i make a size of array 3, 5, 7, 9, … it works correctly. But if a number of lines is 2, 4, 6, … , it is an access violation error, when i try to print my array:
void Print(void){
int i, j;
for(i = 0; i < (n-d); i++){
for(j = 0; j < n; j++){
printf("%d\t", arr[i][j]);
}
printf("\n");
}
}
Looking at this I cannot make sense of…. Look at comment 1, you have
nset somewhere torealloca block of memory whichais of typeint **– a double pointer, how are you calling this function? Secondly, comment 2, Why did you callcallocwhen thereallocon a double pointer was called previously…? Assumenhas value of 5, then,reallocis called on double pointera, meaninga[0][1]..a[4][1], nowcallocis called thusa[4]has a new block of memory…void InsertZero(int **a, int pos){ int i, j; /* 1. */ a = (int**)realloc(a, n * sizeof(*a)); /* Bzzzzt....if realloc failed, a gets overwritten! */ /* 2. */ a[n-1] = (int*)calloc(n, sizeof(**a)); /* 3. */ d = 0; /* 4. */ for(i = n-1; i > pos; i--){ for(j = 0; j < n; j++){ a[i][j] = a[i-1][j]; printf("%d ", a[i][j]); } } for(i = 0; i < n; i++){ a[pos][i] = 0; } }Comment 3, what is
dused for – useless variable?Comment 4, you are under the presumption that the block of memory has array subscripts
[0][0]to[4][4]ifnhad a value of 5!Can you clarify all this?
Edit: Looking at it again… it is likely that
agot overwritten when the call toreallocfailed! I recommend this section of code to counteract thisint **tmpA; tmpA = (int**)realloc(a, n * sizeof(*a)); if (tmpA != NULL){ a = tmpA; .... a[n-1] = (int*)calloc(n, sizeof(**a)); for(i = n-1; i > pos; i--){ .... } for(i = 0; i < n; i++){ .... } }