分割错误在用指针编译C代码时


int main()
{
  long array[1000], *maximum, size, c, location = 1;
  printf("Enter the number of elements in arrayn");
  scanf("%ld", &size);
  printf("Enter %ld integersn", 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定义为long的指针。如果您不将指向指向的指针设置为某件事,则通过阅读和删除无效的指针来调用不确定的行为。

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

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

int main()
{
  long array[1000], maximum, size, c, location = 1;
  printf("Enter the number of elements in arrayn");
  scanf("%ld", &size);
  printf("Enter %ld integersn", 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;
}

您获得分割故障的原因是因为您尝试在未设置maximum时尝试将NULL指针删除。

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

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

最新更新