gpt4 book ai didi

c - 在 C 语言中添加矩阵代码 帮助!我不知道出了什么问题

转载 作者:行者123 更新时间:2023-11-30 19:09:53 24 4
gpt4 key购买 nike

作业要求我们完成一个将矩阵相加的代码,但我不太确定应该返回什么。它告诉我存在运行时错误但我不知道如何解决它。很快就要到期了,所以请有人帮助我!

#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);
}

最佳答案

一些事情:

  • allocateMatrix中,您为n整数分配空间,而不是为指向整数的指针分配空间。

  • 在许多函数中,您使用未初始化的指针C

  • 在许多声明返回某些内容的函数中,您根本不返回任何内容。

这些事情,可能还有其他事情,会导致未定义的行为

关于c - 在 C 语言中添加矩阵代码 帮助!我不知道出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com