c++ - 为什么我的 cpp 数组大小是 4 的倍数?

标签 c++ arrays sizeof

<分区>

我正在尝试创建一个大小为 5 的数组,并获取输入以填充每个索引,然后打印出每个索引处的每个输入。我得到的是数组大小是 4 的倍数。所以当我输入 5 作为大小时,我得到 20 而不是 5。我在这里缺少什么?

#include <iostream>
using namespace std;

int main() {
    int userInput[5];
    cout << sizeof(userInput);

    // take input to fill array
    for (int i = 0; i < sizeof(userInput); i++) {
        cin >> userInput[i];
    }

    // print the array contents
    for (int i = 0; i < sizeof(userInput); i++) {
        cout << userInput[i]
    }
}

最佳答案

这是因为sizeof :

Returns size in bytes of the object representation of type.

不是数组的大小。 (int 的 是 4 个字节长)

关于c++ - 为什么我的 cpp 数组大小是 4 的倍数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52021147/

相关文章:

python - numpy通过任意轴 reshape 多维数组

C++在宏条件中获取类型的大小

c++ - 试图理解数组名称的含义

C 变量在初始化其他变量后变化

c++ - Qt QGraphicsScene 添加和删除线条

java - 使用 arrayList 中的值重用输入 String[]

C++ 参数堆与堆栈,原始类型数组

java - 使用 for 循环将数组复制到另一个数组

C++11 大括号/聚合初始化。什么时候使用它?

c++ - 在 C++ 中全局声明的动态数组的多个定义