У вас есть две основные проблемы в коде.
1) Код, в котором вы инициализируете 2D-массив, должен быть внутри блок if
2) if (height < 0 && width < 0) {
неверно - вы хотите >
вместо <
Попробуйте:
int** make2Darray(int width, int height) {
int **a;
int i = 0;
int j = 0;
/*allocate memory to store pointers for each row*/
a = (int **)calloc(height, sizeof(int *));
if(a != NULL) {
/* allocate memory to store data for each row*/
for(i = 0; i < height; i++) {
a[i] = (int *)calloc(width, sizeof(int));
if(a[i] == NULL) {
/* clean up */
free2Darray(a, height);
return NULL; /*aborting here*/
}
}
// Moved inside the if(a != NULL) {
/* from this point down is the part I implemented, all code above was
given*/
if (height > 0 && width > 0) { // Corrected this part
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
a[i][j] = j;
}
}
}
}
return a;
}
Несколько подсказок:
1) Выполните проверку высоты иширина в начале вашей функции - как:
if (height <= 0 || width <= 0) return NULL;
2) Прототип make2Darray(int width, int height)
кажется мне обратным, поскольку мы обычно упоминаем число строк перед числом столбцов.Я бы предпочел: make2Darray(int height, int width)
.Я даже предпочитаю термин «строка» вместо «высота» и «столбец» вместо «ширина».
3) Ваш текущий код выполняет «все реальные вещи» внутри if(a != NULL) {
Это нормально, но кодбыло бы (для меня) более понятным, если бы вы вместо этого сделали if(a == NULL) return NULL;
4) Нет необходимости разыгрывать calloc
С этими обновлениями код может быть:
int** make2Darray(int rows, int columns) {
int **a;
int i = 0;
int j = 0;
if (rows <= 0 || columns <= 0) return NULL;
a = calloc(rows, sizeof(int*));
if(a == NULL) return NULL;
/* allocate memory to store data for each row*/
for(i = 0; i < rows; i++) {
a[i] = calloc(columns, sizeof(int));
if(a[i] == NULL) {
/* clean up */
free2Darray(a, rows);
return NULL; /*aborting here*/
}
}
/* from this point down is the part I implemented, all code above was
given*/
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
a[i][j] = j;
}
}
return a;
}