gpt4 book ai didi

c - 如何防止我的程序出现此段错误(核心转储)?

转载 作者:行者123 更新时间:2023-11-30 19:32:22 25 4
gpt4 key购买 nike

我有一个程序出现段错误。该程序是一个幻方程序,询问用户一个正方形(矩阵)的大小,然后询问该正方形的行数。我使用一个指针指向声明数组函数中的数组,以引用它在主函数中声明的位置。我想保留指针以便练习使用它们,尽管我知道我可以在没有指针的情况下使程序运行。我认为指针是这里的问题,但我找不到我做错了什么。

这是代码:

int main(void)
{
int *arr[SIZE][SIZE] = "\0";
declareArray(&arr);
declareArray();

return 0;
}
//main logic
int declareArray(int *arr[SIZE][SIZE])
{
//variables
int rowNumber = 0;
int dimension = 0;
//int arr[SIZE][SIZE] = {0};
int row, col;
int sum, sum1, sum2;
int flag = 0;

//ask for input of squares
printf("Please enter the dimension of the square: ");
//makes sure the size is between 1 and 15 for the dimension of the square
if(scanf("%d", &dimension) != 1 || dimension >= 15 || dimension < 1)
{
printf("invalid input\n");
return 1;
}
//enter the data

//array rows
for(row = 0; row < dimension; ++row)
{
printf("Please enter the data for row %d: ", ++rowNumber);
//array columns
for(col = 0; col < dimension; ++col)
{
//store the user input
scanf("%2d", &*arr[row][col]);
}
}
printf("\n");
printf("Here is the square");
printf("\n");
//print the square

//array rows
for(row = 0; row < dimension; ++row)
{
//array columns
for(col = 0; col < dimension; ++col)
{
printf("%d", *arr[row][col]);
}
printf("\n");
}

//Checks Sum of diagonal elements
sum = 0;
for (row = 0; row < dimension; row++) {
for (col = 0; col < dimension; col++) {
if (row == col)
sum = sum + *arr[row][col];
}
}

//Checks Sum of Rows
for (row = 0; row < dimension; row++) {
sum1 = 0;
for (col = 0; col < dimension; col++) {
sum1 = sum1 + *arr[row][col];
}
if (sum == sum1)
flag = 1;
else {
flag = 0;
break;
}
}

//Checks sum of Columns
for (row = 0; row < dimension; row++) {
sum2 = 0;
for (col = 0; col < dimension; col++) {
sum2 = sum2 + *arr[col][row];
}
if (sum == sum2)
flag = 1;
else {
flag = 0;
break;
}
}
//if the sums match, it will print a success message with the constant
//if the sums dont match, a fail message will appear
if (flag == 1)
printf("\nTHE SQUARE IS A MAGIC SQUARE WITH A CONSTANT OF %d \n", sum);
else
printf("\nThe Square is not a magic square \n");


return 0;
}

最佳答案

我在这里看到一些问题

         int *arr[SIZE][SIZE] = "\0"; // this wont compile
declareArray(&arr); // needless
declareArray();
---
int arr[SIZE][SIZE] = {};
declareArray(arr);
//declareArray();

声明函数

 int declareArray(int *arr[SIZE][SIZE]) // because function call changed
---
int declareArray(int arr[SIZE][SIZE])

最后在 printfscanf 中删除不再需要的 * 运算符

    scanf("%2d", &*arr[row][col]); // remove *
---
scanf("%2d", &arr[row][col]);

printf("%d", *arr[row][col]); // remove *
---
printf("%d", arr[row][col]);

sum = sum + *arr[row][col]; // remove *
---
sum = sum + arr[row][col];

关于c - 如何防止我的程序出现此段错误(核心转储)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128977/

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