c++ - C ++:尝试打印指针值时程序崩溃
问题描述
我正在编写一个程序,该程序应该允许用户输入数组的大小,输入数组每个索引的值,并使用指针打印出数组的最小值和最大值。该程序成功地确定了数组的最大值和最小值,并使用指针打印出最大值,但在对最小值指针执行完全相同的操作时会崩溃。
这是代码:
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
程序成功打印最大值,但不是最小值?
解决方案
对于初学者来说,像这样的可变长度数组
int ar[arsize];
不是标准的 C++ 功能。而是使用标准容器std::vector<int>
。
这个电话
fflush(stdin);
具有未定义的行为。去掉它。
在这样的两个 for 循环中
armax = ar[0];
for (i = 0; i < arsize; i++)
{
if (armax < ar[i])
{
armax = ar[i];
ptrmax = &ar[i];
}
}
指针ptrmax
并ptrmin
没有被初始化。因此,通常取消引用指针会导致未定义的行为。
这个输入就是这种情况
Enter value for element at index 0: 50
Enter value for element at index 1: 100
因为最小元素是未设置指针的数组的初始元素。
您可以通过以下方式重写循环
ptrmax = ar;
for (i = 1; i < arsize; i++)
{
if ( *ptrmax < ar[i])
{
ptrmax = ar + i;
}
}
变量armax
和armin
是多余的。
还要记住,有标准算法,std::min_element
可以用来代替循环。std::max_element
std::minmax_element
推荐阅读
- typescript - Jest config (TypeScript): 类型 '{ __PATH_PREFIX__: string; }' 不可分配给类型 'string | 细绳[]'
- arduino - 控制两个 LED 灯串时,ESP32 内核冻结
- arrays - VBA:通过范围与数组更改数据
- java - Mockito 在调用 doCallRealMethod 时抛出 NullpointerException
- javascript - React - 访问导出的常量
- firebase-storage - 将获取的数据存储到状态组件中
- python-3.x - 如何将 python matplotlib.pyplot 图例标记更改为 1、2、3 之类的序列号,而不是形状或字符?
- java - Firebase 中的多态性
- node.js - 程序化 Webpack & Jest (ESM):无法解析没有“.js”文件扩展名的模块
- flutter - 如何修改整个应用程序的 Scaffold 小部件