C++数组中的默认int值问题

6fe3ivhb  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(146)

如何修复数组中默认int值的问题?

#include <iostream>
using namespace std;


int main() {
    int arr[5];
    int size = sizeof(arr) / sizeof(arr[0]);

    

    for (size_t i = 0; i < size; i++)
    {
        int input;
        cout << "Enter num # " << i + 1<<": ";
        cin >> input;
        if (input<-100 || input>100)
        {
            cerr << "Invalid number!";
            break;
        }
        else
        {
            arr[i] = input;
        }
        
    }

    int smallest = arr[0];

    for (int number : arr)
    {
        if (number<smallest)
        {
            smallest = number;
        }
    }

    cout << "The smallest number is: " << smallest;

}

默认的int值是634906509还是类似的东西?

vpfxa7rd

vpfxa7rd1#

提前感谢!默认int value = 634906509类似的东西
数组中的默认值是未定义的(可以是任何值)。有些系统在调试模式下会对未初始化的内存使用标准模式。但你不能指望这一点,在生产中这不太可能发生。
要默认初始化数组,可以执行以下操作:

int arr[5] = {0}; // Sets all values to zero.

如果你想用其他东西初始化所有的值,你需要具体。

int arr[5] = {1,2,3,4,5};

旁注:这是C,不是C++的好做法。

int size = sizeof(arr) / sizeof(arr[0]);
// The problem is that arrays turn into pointers very easily
// if you modify the code and this will still compile but
// give you the completely wrong answer.

试试看:

std::size_t size = std::size(arr);

相关问题