Проблема с добавлением двух матриц с использованием многомерных массивов

Кажется, я получаю ввод для первой матрицы, но когда я прошу пользователя ввести ввод для второй матрицы, программа вылетает.. почему это? не могу понять, я даже пробовал выделить память, результат тот же...

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

#define MAXCOLUMNS 10 

// dealing with 2D arrays, passing to function etc
void read_input(int (*a)[MAXCOLUMNS], int n_rows, int n_columns);
void print_sum (int (*a)[MAXCOLUMNS], int (*b)[MAXCOLUMNS], int (*c)[MAXCOLUMNS], int    n_rows, int n_columns);

int main() {
    int i;
    int rows;
    int columns;

    int (*two_d_array)[MAXCOLUMNS];
    int (*two_d_array2)[MAXCOLUMNS];    
    int (*output)[MAXCOLUMNS];

    printf("enter the number of rows\n");
    scanf("%d", &rows);

    printf("enter the number of columns\n");
    scanf("%d", &columns);

    printf("enter data into array number 1\n");
    read_input(two_d_array, rows, columns);

    printf("enter data for 2d array number 2\n");
    read_input(two_d_array2, rows, columns);

    print_sum(two_d_array, two_d_array2, output, rows, columns);

    return 0;
}

void read_input(int (*a)[MAXCOLUMNS], int n_rows, int n_columns) {
    int i;
    int j;

    for (i = 0; i < n_rows; ++i) {
        for (j = 0; j < n_columns; ++j) {
            printf("enter details for rows number %d and column number %d\n", i + 1, j + 1);
            scanf("%d", (*(a+i)+j));
            getchar();
        }
    }   
}

void print_sum (int (*a)[MAXCOLUMNS], int (*b)[MAXCOLUMNS], int (*c)[MAXCOLUMNS], int n_rows, int n_columns) {
    int i;
    int j;

    // computing sum
    for (i = 0; i < n_rows; i++) {
        for (j = 0; j < n_columns; j++) {
            *(*(c+i)+j) = *(*(a+i)+j) + *(*(b+i)+j);
        }
    }

    // printing sum
    for (i = 0; i < n_rows; i++) {
        printf("\n");
        for (j = 0; j < n_columns; j++) {
            printf("%d\t", *(*(c+i)+j));
        }
    }
}

person user3151918    schedule 01.01.2014    source источник
comment
даже пробовал выделять память — и перестал это делать, почему именно? Вы думаете, что любая ошибка, которая у вас была, и ошибка невыделения памяти там, где она нужна, каким-то образом компенсируется?   -  person n. 1.8e9-where's-my-share m.    schedule 02.01.2014
comment
Я не запускал ваш код, но вы должны хотя бы инициализировать свои массивы, например, int (*two_d_array)[MAXCOLUMNS] = NULL;   -  person Bruce Dean    schedule 02.01.2014
comment
@n.m я пытался выделить память вот так   -  person user3151918    schedule 02.01.2014
comment
two_d_array[i] = (int*) malloc (столбцы * sizeof(int)); two_d_array2[i] = (int*) malloc (столбцы * sizeof(int)); output[i] = (int*) malloc (столбцы * sizeof(int)); @n.m   -  person user3151918    schedule 02.01.2014
comment
но он говорит о несовместимых типах в назначении, где я ошибаюсь? @BLUEPIXY   -  person user3151918    schedule 02.01.2014
comment
Отредактируйте свой вопрос, если хотите добавить новую информацию. Код в комментариях не читается. (Кстати, удаление строк кода, на которые жалуется компилятор, не очень хорошая стратегия исправления ошибок).   -  person n. 1.8e9-where's-my-share m.    schedule 02.01.2014
comment
@BLUEPIXY, так как я пробовал и делал это неправильно.   -  person user3151918    schedule 02.01.2014
comment
где я ошибаюсь? Не был должным образом защищен память.   -  person BLUEPIXY    schedule 02.01.2014
comment
@BLUEPIXY, можете ли вы ввести пример того, как выделить память для 2d-массива?   -  person user3151918    schedule 02.01.2014
comment
Я думаю, что это хорошее начало int ** Если вам не нужно придерживаться MAXCOLUMNS.   -  person BLUEPIXY    schedule 02.01.2014


Ответы (1)


для C99

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

#define MAXCOLUMNS 10 

void read_input(int rows, int cols, int a[rows][cols]);
void print_sum (int rows, int cols, int in1[rows][cols], int in2[rows][cols], int out[rows][cols]);

int main(void) {
    int i, rows, columns;

    printf("enter the number of rows\n");
    scanf("%d", &rows);

    printf("enter the number of columns\n");
    scanf("%d", &columns);
    //if(columns > MAXCOLUMNS){ fprintf(stderr, "too large!"); return 1); }
    int array1[rows][columns];
    int array2[rows][columns];
    int array3[rows][columns];

    printf("enter data into array number 1\n");
    read_input(rows, columns, array1);

    printf("enter data for 2d array number 2\n");
    read_input(rows, columns, array2);

    print_sum(rows, columns, array1, array2, array3);

    return 0;
}

void read_input(int rows, int cols, int a[rows][cols]){
    int i, j;

    for (i = 0; i < rows; ++i) {
        for (j = 0; j < cols; ++j) {
            printf("enter details for rows number %d and column number %d\n", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }
    }   
}

void print_sum (int rows, int cols, int a[rows][cols], int b[rows][cols], int c[rows][cols]){
    int i, j;

    for (i = 0; i < rows; i++){
        printf("\n");,,
        for (j = 0; j < cols; j++){
            c[i][j] = a[i][j]  + b[i][j];
            printf("%d\t", c[i][j]);
        }
    }
}

для int** (2D_ARRAY)

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

int main(void){
    int rows = 3;
    int cols = 5;
    int **array;
    int r, c;
    //allocate
    array = malloc(rows * sizeof(int*));
    for(r = 0; r < rows ; ++r){
        array[r] = malloc(cols * sizeof(int));
    }
    //set
    for(r = 0; r < rows ; ++r){
        for(c = 0; c < cols ; ++c){
            array[r][c] = r * 10 + c;
        }
    }
    //print
    for(r = 0; r < rows ; ++r){
        for(c = 0; c < cols ; ++c){
            printf("%02d ", array[r][c]);
        }
        printf("\n");
    }
}

для целых (**)[РАЗМЕР]

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

#define MAX 10

int main(void){
    int rows = 3;
    int cols = 5;
    int (**array)[MAX];
    int r, c;
    //allocate
    array = malloc(rows * sizeof(int (*)[MAX]));
    for(r = 0; r < rows ; ++r){
        array[r] = malloc(sizeof(int[MAX]));
    }
    //set
    for(r = 0; r < rows ; ++r){
        for(c = 0; c < cols ; ++c){
            (*array[r])[c] = r * 10 + c;
        }
    }
    //print
    for(r = 0; r < rows ; ++r){
        for(c = 0; c < cols ; ++c){
            printf("%02d ", (*array[r])[c]);
        }
        printf("\n");
    }
}

для целых (*)[РАЗМЕР]

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

#define MAX 10

int main(void){
    int rows = 3;
    int cols = 5;
    int (*array)[MAX];
    int r, c;
    //allocate
    array = malloc(rows * sizeof(int[MAX]));
    //set
    for(r = 0; r < rows ; ++r){
        for(c = 0; c < cols ; ++c){
            array[r][c] = r * 10 + c;
        }
    }
    //print
    for(r = 0; r < rows ; ++r){
        for(c = 0; c < cols ; ++c){
            printf("%02d ", array[r][c]);
        }
        printf("\n");
    }
}
person BLUEPIXY    schedule 01.01.2014
comment
когда используется **массив[MAX]? это другой способ записи (*array)[MAXSIZE] или это массив указателей, например *array[MAXSIZE]? @BLUEPIXY - person user3151918; 02.01.2014
comment
и как мне узнать, когда писать malloc, как этот array[i] =int*malloc(columns * sizeof(int)); где я увеличивается в цикле for до максимального количества строк, а столбцы представляют максимальное количество. столбцов, почему вы не умножили столбцы на sizeof int в примере с массивом **? @BLUEPIXY - person user3151918; 02.01.2014
comment
array = malloc (строки sizeof(int()[MAXSIZE])); for ( i = 0; i ‹ rows ; i ++) array[i] = malloc(sizeof(int[MAXSIZE])); // я пытался выделить память так, как вы сказали, но он говорит о несовместимых типах в назначении.. - person user3151918; 02.01.2014
comment
@ user3151918 почему вы не перемножили столбцы с sizeof int в **примере с массивом? array[r] = malloc(cols * sizeof(int)); я умножил столбец. - person BLUEPIXY; 02.01.2014
comment
@user3151918 array = malloc (размер строк (int () [MAXSIZE])); for ( i = 0; i ‹rows ;i ++) array[i] = malloc(sizeof(int[MAXSIZE])); Это кажется неправильным во многих отношениях. - person BLUEPIXY; 02.01.2014
comment
@user3151918 **array[MAX] , (*array)[MAXSIZE] , *array[MAXSIZE] , это другое - person BLUEPIXY; 02.01.2014