2013-03-23 237 views
3

评论公正地解释了这一切。帮帮我?字符串矩阵的sizeof

string aZOM[][2] = {{"MoraDoraKora", "PleaseWorkFFS"},{"This is a nother strang.", "Orly?"}}; 
cout << sizeof("MoraDoraKora") <<" \n"; 
//Obviously displayes the size of this string... 
cout << sizeof(aZOM[0][0]) << " \n"; 
//here's the problem, it won't display the size of the actual string... erm, what? 

string example = aZOM[0][0]; 
cout << example << " \n"; 
cout << aZOM[0][1] << " \n"; 
//Both functions display the string just fine, but the size of referencing the matrix is the hassle. 

回答

4

sizeof给你,你传递给它以字节为单位的对象的大小。如果你给它一个std::string,它会给你std::string对象本身的大小。现在,我的对象为实际字符动态分配存储空间,并包含一个指向它们的指针,但这不是对象本身的一部分。

要获得std::string的大小,使用其size/length成员函数:

cout << aZOM[0][1].size() << " \n"; 

sizeof("MoraDoraKora")正常工作的原因是因为字符串文字"MoraDoraKora"一个std::string对象。它的类型是“13 constchar1阵列”等sizeof报告以字节数组的大小。

+0

注意;对于第一个你得到一个const char *的大小? – Skeen 2013-03-23 00:30:34

+0

这似乎是更好的解释。 :) – scones 2013-03-23 00:31:18

+0

@Skeen你得到数组的大小,因为数组不会经历数组到指针的转换作为'sizeof'的操作数。 – 2013-03-23 00:31:48

2
sizeof

返回类型的大小,而不是数据的大小指向。

一个字符串,通常是一个字符指针,在生产链的最后一个字符的值为0

如果你想字符串的实际大小,你可以使用aZOM[0][0].length()