Artur Yuzkiv Artur Yuzkiv - 9 months ago 40
C Question

Using realloc() function in C for increasing column in 2D array

I have the following code which must resize a column of matrix of 2D array:



#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]){

int n = 3;
int m = 4;
int * * mas = malloc(n * sizeof( * mas));

for (int i = 1; i < n + 1; i++) {
mas[i] = malloc(m * sizeof( * (mas[i])));
}
for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < m; j++) {
mas[i][j] = i + 1;
printf("%d ", mas[i][j]);
}
printf("\n");
}
printf("\n");


when I resize a column of matrix(but leave the same size of rows) it finish starting a loop:

for (int i = 1; i < n + 1; i++) {
int * tmp = realloc(mas[i], (m + 1) * sizeof( * mas[i]));
if (tmp) {
mas[i] = tmp;
}
}

mas[1][4] = 100;
mas[2][4] = 200;
mas[3][4] = 300;

for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < m + 1; j++) {
printf("%d ", mas[i][j]);
}
printf("\n");
}
for(int i = 1; i< n+1; i++){
free(mas[i]);
}
free(mas);
system("pause");
return 0;
}





I have:
2 2 2 2
3 3 3 3
4 4 4 4





after printing this myprg.exe finished



but when I do resize with simple vector it've done!

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[]) {
int n = 3;
int m = 4;
int* mas = malloc(n*sizeof(mas));

for(int i = 1; i < n+1; i++){
mas[i] = 0;
}
for(int i = 1; i < n+1; i++){
printf("%d\n", mas[i]);
}
mas = realloc(mas, (n+2)*sizeof(*mas));
for(int i = 1; i < n+3; i++){
mas[i] = 0;
}
for(int i = 1; i < n+3; i++){
printf("%d\n", mas[i]);
}
free(mas);
system("pause");
return 0;
}





I think it's something with pointer of 2D array, but I don't understand what exactly :(

Answer Source

Replace every for (int i = 1; i < n + 1; i++) with for (int i = 0; i < n; i++) in your code. Array indices goes from 0 to n-1 not 1 to n

Similarly, change

mas[1][4] = 100;
mas[2][4] = 200;
mas[3][4] = 300;

to

mas[0][4] = 100;
mas[1][4] = 200;
mas[2][4] = 300;

for the same reason.

It is better to check the return value of those mallocs as well to see if they were successful or not. Also, you should take proper action if the realloc failed and tmp is NULL.