簡體   English   中英

C++:嘗試打印指針值時程序崩潰

[英]C++: Program crashes when trying to print value of pointer

我正在編寫一個程序,它應該允許用戶輸入數組的大小,輸入數組每個索引的值,並使用指針打印出數組的最小值和最大值。 該程序成功地確定了數組的最大值和最小值,並使用指針打印出最大值,但在對最小值指針執行完全相同的操作時會崩潰。

這是代碼:

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

指針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代替循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM