首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我的cpp数组大小是4的倍数?

为什么我的cpp数组大小是4的倍数?
EN

Stack Overflow用户
提问于 2018-08-26 04:54:39
回答 3查看 192关注 0票数 0

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

代码语言:javascript
运行
复制
#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]
    }
}
EN

回答 3

Stack Overflow用户

发布于 2018-08-26 04:58:09

这是因为sizeof

返回类型的对象表示形式的字节大小。

而不是数组的大小。(int's为4字节长)

票数 2
EN

Stack Overflow用户

发布于 2018-08-26 04:59:41

来自cppreference.com

sizeof:返回类型的对象表示形式的大小,单位为字节

现在,由于int需要4字节(这是编译器的implementation defined特性),因此int[5]数组的大小将为5*4=20 bytes

如果想要获得数组的大小,可以使用(正如Deduplicator在注释中指出的那样):

代码语言:javascript
运行
复制
std::size( userInput );

在这种情况下,不要忘记使用#include <iterator>

票数 2
EN

Stack Overflow用户

发布于 2018-08-26 05:19:40

或者,要获得C数组的大小,可以在支持C++17的编译器上使用std::size()函数:

代码语言:javascript
运行
复制
#include <iostream>

int main() {
    int userInput[5];
    int arrsize = static_cast<int>(std::size(userInput));

    for (auto i = 0; i < arrsize; i++) {
        std::cin >> userInput[i];
    }

    for (auto i = 0; i < arrsize; i++) {
        std::cout << userInput[i];
    }
}

您可以使用range-based for loops来简化操作

代码语言:javascript
运行
复制
#include <iostream>

int main() {
    int userInput[5];
    for (auto& el : userInput) {
        std::cin >> el;
    }
    for (auto el : userInput) {
        std::cout << el;
    }
}

或者将C样式数组替换为std::array包装器:

代码语言:javascript
运行
复制
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> userInput;
    for (auto& el : userInput) {
        std::cin >> el;
    }
    for (auto el : userInput) {
        std::cout << el;
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52021147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档