首页 > 解决方案 > 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

程序成功打印最大值,但不是最小值?

标签: c++algorithmloopsfor-looppointers

解决方案


对于初学者来说,像这样的可变长度数组

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];
    }
}

指针ptrmaxptrmin没有被初始化。因此,通常取消引用指针会导致未定义的行为。

这个输入就是这种情况

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;
    }
}

变量armaxarmin是多余的。

还要记住,有标准算法,std::min_element可以用来代替循环。std::max_elementstd::minmax_element


推荐阅读