【发布时间】:2011-12-22 11:51:48
【问题描述】:
我不断收到分段错误,但我不确定这意味着什么或如何判断导致它的原因(我对编程和 C 语言非常陌生)。在这个由 main.c 调用的函数中,我需要确定二维数组的 eacg 行中最小数字的索引。
这是我的代码:
#include "my.h"
void findfirstsmall (int x, int y, int** a)
{
int i;
int j;
int small;
small = y - 1;
printf("x = %3d, y = %3d\n", x, y); //trying to debug
printf("f. The first index of the smallest number is: \n");
for(i = 0; i < x; i++)
{
for(j = 0; j < y; i++) <---------- needs to be j, for any future readers
{
if(a[i][small] > a[i][j])
small = j;
printf("small = %3d\n", small); //trying to debug
}
printf("Row: %4d, Index: %4d\n", i, small);
small = y - 1;
printf("\n");
}
printf("\n");
return;
}
第一行打印正确,但第二行打印不正确。 这是我的数组:
56 7 25 89 4
-23 -56 2 99 -12
这是我运行程序时得到的:
x = 2, y = 5 f. The first index of the smallest number is: small = 4 small = 0 Segmentation fault
这是在 C 中。提前感谢您的帮助!
【问题讨论】:
-
分段错误通常是因为您不正确地访问内存而发生的。因此,例如,这里可能发生这种情况,因为您读取数组的逻辑导致程序在“a”数组之外读取。您能否将您的定义也包含在“main.c”中?
-
是的,向我们展示您传递参数的代码以及如何确定它们,尤其是数组。此外,您可以使用调试器一次单步执行一行代码,以查看它崩溃的位置。
-
a的意思是int **,而不是int *加上一个行步幅? -
您应该阅读this question 了解有关分段错误的更多信息
-
发布您如何分配
a。问题可能是它不正确malloced
标签: c multidimensional-array segmentation-fault