c++ - 使用 auto 关键字初始化 char 数组

标签 c++ auto

我一直在测试 auto 关键字,发现了一些对我来说很奇怪的事情。每个字母占用 1 个字节(char 类型),使用自动变量的自动说明符大小无论如何都是 4 个字节(我没有测试很长的字符串)。怎么解释呢?

char carray[] = "Some test output";
auto variable = "Some test output";

cout<<"carray: "<<sizeof(carray)<<endl;
cout<<"auto: "<<sizeof(variable);

最佳答案

由于数组到指针的衰减,variable 变成了 const char*(大小为 4,这让我有些惊讶 - 你的平台是什么?) .

如果你想让你的变量保持一个字符数组,你可以使用decltype(auto),比如

decltype(auto) variable = "Some test output"; // sizeof(variable) is 17

关于c++ - 使用 auto 关键字初始化 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54581817/

相关文章:

c++ - 如何以其他方式或转换案例格式编码auto&?

c++ - 是否可以有一个 "auto"成员变量?

c++ - 使用Android NDK在constexpr构造函数(c++ 17)中分配给const char *失败

c++ - 使用 '&'进行迭代时 'auto'符号有什么作用

c++ - `auto const& x `在C++中做什么?

c++ - 如何使用继承在作为类成员的结构中添加新条目

c++ - 返回 'auto' 的函数在定义之前不能使用

c++ - 如何使用 C++ 在 Windows 中列出子目录?我需要单独使用 Windows API 的解决方案

c++ - 无法显示我每个功能的结果

c++ - 创建友元函数时出错, "coins does not name a type"