我一直在测试 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/