【发布时间】:2020-10-19 10:42:27
【问题描述】:
我正在编写一个程序,它应该允许用户输入数组的大小,输入数组每个索引的值,并使用指针打印出数组的最小值和最大值。程序成功确定数组的最大值和最小值,并使用指针打印出最大值,但在对最小值指针执行完全相同的操作时会崩溃。
代码如下:
int main()
{
//Variable Declaration
int arsize = 0;
int i = 0;
int range = 0;
int armin, armax;
int *ptrmin, *ptrmax;
//User Prompt for array size, saved to variable arsize
printf("How many elements should be stored in the array?: ");
scanf("%d", &arsize);
fflush(stdin);
//The array ar is declared according to the user input
int ar[arsize];
for (i = 0; i < arsize; i++)
{
printf("Enter value for element at index %d:\t", i);
scanf("%d", &ar[i]);
fflush(stdin);
}
//For loop with if statement to determine biggest value in array 'ar'
armax = ar[0];
for (i = 0; i < arsize; i++)
{
if (armax < ar[i])
{
armax = ar[i];
ptrmax = &ar[i];
}
}
//For loop with if statement to determine the smallest value in array 'ar'
armin = ar[0];
for (i = 0; i < arsize; i++)
{
if (armin > ar[i])
{
armin = ar[i];
ptrmin = &ar[i];
}
}
//The Min and Max is printed using pointers, Range is printed regularly
printf("\nMax:\t%d\n", *ptrmax);
printf("Min:\t%d\n", *ptrmin);
输出如下:
How many elements should be stored in the array?: 2
Enter value for element at index 0: 50
Enter value for element at index 1: 100
Max: 100
Process returned -1073741819 (0xC0000005) execution time : 4.438 s
程序成功打印最大值,但不是最小值?
【问题讨论】:
-
如果
ar[0]是最小值,则您没有将ptrmin设置为任何值。ptrmax也有同样的问题。 -
你用
armax = ar[0];和armin = ar[0];做正确的事,为什么不ptrmin/ptrmax呢? -
顺便说一句,
fflush(stdin)is not correct.
标签: c++ algorithm loops for-loop pointers