开发一个小控制台应用程序,该应用程序对相似维度矩阵中的值执行数学运算。CreateMatrix(( 函数返回给出数组尺寸的 int**,现在我正在尝试接受输入并遇到错误。我以前从未使用过malloc,所以我认为我用错了东西。我将尝试省略查找我的问题时不需要的任何代码。
int rowInput, colInput;
int** customA, customB;
int main(void) {
printf("nEnter the number of Rows: ");
scanf(" %i", &rowInput);
printf("nEnter the number of Columns: ");
scanf(" %i", &colInput);
customA = CreateMatrix(colInput, rowInput);
for (int row = 0; row <= rowInput; row++) {
for (int column = 0; column <= colInput; column++) {
printf("Enter input for value at MatrixA[%d][%d]n", row, column);
scanf(" %i", &customA[row][column]);
}
}
PrintMatrix(rowInput, colInput, customA);
printf(" n");
}
}
CreateMatrix(( 和 include, 在我的 Header.h 中声明
#include <stdio.h>
#include <stdlib.h>
#define Row 2
#define Col 5
#define Max 10
/**
*Dynamically allocate memory for custom matrix based on desired dimensions input
*@return int** to newly allocated matrix
**/
int** CreateMatrix(int colInput, int rowInput);
/**
*Checks input for matrix Row and columns exceeding maximum allowed
*
*/
int CheckMaximums(int *rowInput, int *colInput);
CreateMatrix((是在我的CLibrary.c中定义的,我已经在CMake中链接了它。包含 CheckMaximums(( 仅供您参考,因为它在 CreateMatrix 中使用。不过,我对这种逻辑没有问题。
#include <Header.h>
int** CreateMatrix(int colInput, int rowInput) {
int** customMatrix;
CheckMaximums(&rowInput, &colInput);
printf(" n");
customMatrix = (int**)malloc(rowInput);
for (int i = 0; i < colInput; i++)
customMatrix = (int*)malloc(colInput);
return customMatrix;
}
int CheckMaximums(int *rowInput, int *colInput) {
if (*rowInput > Max || *colInput > Max) {
if (*rowInput > Max && *colInput > Max) {
*rowInput = Max;
*colInput = Max;
printf("nYour Row and Column sizes both exceed the maximum allowed valuesn"
"Row size has been set to max value (10)n"
"Column size has been set to max value (10)");
}
else if (*rowInput > Max) {
*rowInput = Max;
printf("nYour Row size exceeds the maximum allowed valuen"
"Row size has been set to max value (10)n");
}
else {
*colInput = Max;
printf("nYour Column size exceeds the maximum allowed valuen"
"Column size has been set to max value (10)n");
}
}
}
提前感谢,我知道这有很多值得关注的地方,试图将其减少到最低限度!
在 CreateMatirx 中,malloc 需要知道要分配的总字节数。将所需的元素数乘以每个元素的大小。
customMatrix = malloc(rowInput * sizeof ( int*);//each element is a pointer to int
for (int i = 0; i < rowInput; i++)
customMatrix[i] = malloc(colInput * sizeof int);//each element is an int
第一个 malloc 为rowInput
指针分配足够的内存。每个指针都可以像数组一样访问,其索引customMatrix[0]
到 customMatrix[rowInput - 1]
。for
循环遍历每个指针,并为colInput
整数分配足够的内存。
在 main 中,将 <= 更改为 for 循环中的 <,否则您将访问超出分配的内存
for (int row = 0; row < rowInput; row++) {
for (int column = 0; column < colInput; column++) {
应检查 Malloc 和 SCANF 的返回,因为这些函数可能会失败