[英]C Segmentation Fault in Sub-function: How do I know what to fix? What is a segmentation fault?
我一直遇到分段錯誤,但是我不確定這是什么意思或如何確定是什么原因造成的(我對編程和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語言。在此先感謝您的幫助!
解決typo
:
for(j = 0; j < y; j++)
^^
分段錯誤表示您正在訪問您不擁有的內存。
無需查看您的代碼即可立即猜測-這是一個錯誤的提示。 請記住,C數組基於零。
我將盡快查看您的代碼。
printf("f. The first index of the smallest number is: \n");
for(i = 0; i < x; i++)
{
for(j = 0; j < y; i++) // my guess is that you increment "i" instead of "j"
{
請注意,二維數組和指針數組之間有區別(請參閱此問題 )。 根據您在main()
,這可能是您的問題。 例如,以下代碼不能按原樣使用該函數,因為它會將指針傳遞給包含數組數組的內存:
int arr[2][5] = { { 56, 7, 25, 89, 4 },
{ -23, -56, 2, 99, -12 } };
findfirstsmall (2, 5, arr);
但是,這沒關系,因為它將指針數組傳遞到arr
的每個子數組的開頭:
int arr[2][5] = { { 56, 7, 25, 89, 4 },
{ -23, -56, 2, 99, -12 } };
int *tmp[2];
tmp[0] = &arr[0][0];
tmp[1] = &arr[1][0];
findfirstsmall (2, 5, tmp);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.