Die Aufgabe fordert uns auf, einen Code zu beenden, der Matrizen hinzufügt und ich bin mir nicht sicher, was ich zurückgeben soll. Es sagt mir, dass es einen Laufzeitfehler gibt, aber ich weiß nicht, wie man es repariert. Es wird ziemlich bald fällig sein, also bitte jemand mir helfen!Matrizencode in C hinzufügen HILFE! Ich weiß nicht, was los ist
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int** getMatrix(int n, int m);
int** allocateMatrix(int n, int m);
int** addMatrices(int** A, int** B, int n, int m);
void printMatrix(int** A, int n, int m);
void deallocateMatrix(int** A, int n);
// This program reads in two n by m matrices A and B and
// prints their sum C = A + B
//
// This function is complete, you do not need to modify it
// for your homework
int main() {
int n = 0, m = 0;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &n, &m);
assert(n > 0 && m > 0);
printf("Enter matrix A:\n");
int** A = getMatrix(n, m);
printf("Enter matrix B:\n");
int** B = getMatrix(n, m);
int** C = addMatrices(A, B, n, m);
printf("A + B = \n");
printMatrix(C, n, m);
deallocateMatrix(A, n);
deallocateMatrix(B, n);
deallocateMatrix(C, n);
}
// Creates a new n by m matrix whose elements are read from stdin
//
// This function is complete, you do not need to modify it
// for your homework
int** getMatrix(int n, int m) {
int** M = allocateMatrix(n, m);
int i, j;
for (i = 0; i < n; i++) {
printf("Input row %d elements, separated by spaces: ", i);
for (j = 0; j < m; j++) {
scanf("%d", &M[i][j]);
}
}
return M;
}
// Allocates space for an n by m matrix of ints
// and returns the result
int** allocateMatrix(int n, int m) {
// Homework TODO: Implement this function
int i, j;
int** L;
L = (int**)malloc(sizeof(int) * n);
for(i = 0; i < n; i++) {
for(j = 0; j < m; j++){
L[i] = (int*) malloc(sizeof(int) * m);
}
}
}
// Adds two matrices together and returns the result
int** addMatrices(int** A, int** B, int n, int m) {
// Homework TODO: Implement this function
int j, i;
int** C;
for(i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}
// Prints out the entries of the matrix
void printMatrix(int** A, int n, int m) {
// Homework TODO: Implement this function
int i, j;
int** C;
for (i = 0; i < n; i++) {
for (j = 0 ; j < m; j++) {
printf("%d\t", C[i][j]);
}
printf("\n");
}
}
// Deallocates space used by the matrix
void deallocateMatrix(int** A, int n) {
int i;
for (i = 0; i < n; i++) {
free(A[i]);
}
free(A);
}
Unabhängig von Ihren Problemen, aber bitte [lesen Sie diese Diskussion] (http://Stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) über das Gießen des Ergebnisses von ' malloc'. –
In Ordnung, werde ich. Vielen Dank! – Sara