c++ - C++上数组错误的大小

标签 c++

<分区>

我正在尝试获取数组大小,但出现错误。我的代码是:

#include <iostream>
#include <array>

using namespace std;
int main ()
{
 int myarray[5];
  cout << "size of array: " << myarray.size() << endl;
  cout << "sizeof array: " << sizeof(myarray) << endl;

  return 0;
}

这是我遇到的错误:

error: request for member 'size' in 'myarray', which is of non-class type 'int [5]'|

最佳答案

数组没有成员函数,因为它们不是类。但是如果你使用 std::array那么你可以使用成员函数 size

例如

#include <iostream>
#include <array>

using namespace std;
int main ()
{
  std::array<int, 5> myarray;

  cout << "size of array: " << myarray.size() << endl;
  cout << "sizeof array: " << sizeof(myarray) << endl;

  return 0;
}

如果你确实想处理一个数组,那么程序可以像下面这样

#include <iostream>
#include <type_traits>

int main()
{
    int myarray[5];

    std::cout << "sizeof myarray: " 
              << sizeof( myarray ) << std::endl;

    std::cout << "size of myarray: " 
              << sizeof( myarray ) / sizeof( *myarray ) << std::endl;

    std::cout << "size of myarray: " 
              << std::extent<decltype( myarray )>::value << std::endl;

    return 0;
}

程序输出为

sizeof myarray: 20
size of myarray: 5
size of myarray: 5

关注标准类std::extent在 header 中声明 <type_traits>

关于c++ - C++上数组错误的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683864/

相关文章:

c++ - 使用函数指针将 C 转换为 CPP

c++ - 可怕的数字不知从何而来

c++ - 带有 GUI 的 Qt 多线程

c++ - C++如何在字符串数组中查找字符串

c++ - 我如何在 Symbian 上检索 SMS 收件箱消息,最好使用 j2me?

c++ - 如何保持 QSlider 处于激活状态以允许随时使用箭头移动

c++ - "unpacking"调用匹配函数指针的元组

c++ - 如何判断一个类型是否真正可 move 构造

c++ - 二维数组和文件处理 [C++]

c++ - 如何在 Qt 中弹出消息窗口?