使用指针编译C代码时出现分段错误

时间:2019-02-27 15:23:30

标签: c arrays pointers

int main()
{
  long array[1000], *maximum, size, c, location = 1;

  printf("Enter the number of elements in array\n");
  scanf("%ld", &size);

  printf("Enter %ld integers\n", size);

  for ( c = 0 ; c < size ; c++ )
    scanf("%ld", &array[c]);

   maximum  = array;
  *maximum = *array;

  for (c = 1; c < size; c++)
  {
    if (*(array+c) > *maximum)
    {
       *maximum = *(array+c);
       location = c+1;
    }
  }

  printf("Maximum element is present at location number %ld and it's value is %ld.\n", location, *maximum);
  return 0;
}

在这段代码中找到一个数组中的最大值,而没有'maximum = array',我遇到了分段错误。这可能是什么原因?

2 个答案:

答案 0 :(得分:2)

maximum被定义为指向long的指针。如果未将指针设置为指向某对象,则可以通过读取并取消引用无效的指针来调用undefined behavior

此外,由于您将maximum指向数组的第一个元素,因此每次更新*maximum时,您都在更改数组中的第一个值,这可能不是您想要的。

实际上并不需要maximum作为指针,因此将定义更改为long并相应地更改引用。

int main()
{
  long array[1000], maximum, size, c, location = 1;

  printf("Enter the number of elements in array\n");
  scanf("%ld", &size);

  printf("Enter %ld integers\n", size);

  for ( c = 0 ; c < size ; c++ )
    scanf("%ld", &array[c]);

   maximum = array[0];

  for (c = 1; c < size; c++)
  {
    if (array[c]) > maximum)
    {
       maximum = array[c]);
       location = c+1;
    }
  }

  printf("Maximum element is present at location number %ld and it's value is %ld.\n", location, maximum);
  return 0;

}

答案 1 :(得分:1)

出现分段错误的原因是,当未设置NULL时,您试图取消引用maximum指针。

正确的方法是(如您的代码中所述):

   maximum  = array;  // set the pointer to 'array'
  *maximum = *array;  // then de-reference.