C ++:尝试打印指针值时程序崩溃

时间:2020-10-19 10:42:27

标签: c++ algorithm loops for-loop pointers

我正在编写一个程序,该程序应该允许用户输入数组的大小,输入数组每个索引的值,并使用指针打印出数组的Min和Max Values。该程序成功确定了数组的“最大值”和“最小值”,并使用指针打印出了最大值,但对最小值指针执行完全相同的操作时会崩溃。

这是代码:

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

程序成功打印出最大值,但没有打印出最小值?

1 个答案:

答案 0 :(得分:0)

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

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_elementstd::max_elementstd::minmax_element代替循环。

相关问题