【问题标题】:C Segmentation Fault in Sub-function: How do I know what to fix? What is a segmentation fault?子功能中的 C 分段错误:我怎么知道要修复什么?什么是分段错误?
【发布时间】: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


【解决方案1】:

修复typo

       for(j = 0; j < y; j++)
                         ^^

【讨论】:

    【解决方案2】:

    分段错误意味着您正在访问不属于您的内存。

    无需查看代码即可即时猜测 - 这是一个错误的错误。记住 C 数组是从零开始的。

    我会尽快查看您的代码。

    【讨论】:

    • 快速提示 = 通常使用无符号整数进行数组访问
    【解决方案3】:
    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"
               {
    

    【讨论】:

      【解决方案4】:

      请注意,二维数组和指针数组之间存在差异(请参阅this question)。根据您在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);
      

      【讨论】:

        猜你喜欢
        • 2019-05-31
        • 2018-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 2021-07-12
        相关资源
        最近更新 更多