使用一个小型控制台应用程序,该应用程序对类似维度的矩阵的值执行数学运算。 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()和includes,在我的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 values\n"
"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 value\n"
"Row size has been set to max value (10)\n");
}
else {
*colInput = Max;
printf("\nYour Column size exceeds the maximum allowed value\n"
"Column size has been set to max value (10)\n");
}
}
}
在此先感谢,我知道这很重要,试着将其减少到最低限度!
答案 0 :(得分:1)
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中,将&lt; =更改为&lt;在for循环中,否则你访问超出分配的内存
for (int row = 0; row < rowInput; row++) {
for (int column = 0; column < colInput; column++) {
应该检查malloc和scanf的返回,因为这些函数可能会失败