是否有可能获得包含字面值的字符串的长度

Is it possible to get the length of a string including literals

本文关键字:字符串 字面值 包含 有可能 是否      更新时间:2023-10-16

例如,"helloworld"将返回长度12,因为字符串中有12个字符。

您可以使用sizeof:

char h[] = "helloworld";
std::cout << sizeof(h);

char类型的内存分配取决于操作系统(16位,32位操作系统等)。在某些操作系统中,为char类型的数据分配了2个字节。所以运行下面的代码&它将在所有操作系统中给出相同的结果:

#include<iostream.h>
int main()
 {
            char h[] = "helloworld";
            cout<<sizeof(h)/sizeof(char);
            return 0;
 }