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.