我对C ++中的sizeof字符串数组感到困惑,我有以下字符串数组:
static const char* namedButtonStr[] = {
"GLUT_LEFT_BUTTON",
"GLUT_MIDDLE_BUTTON",
"GLUT_RIGHT_BUTTON"
};
为了获得此数组的大小,使用了以下代码:
int size = int(sizeof(namedButtonStr)/sizeof(namedButtonStr[0]));
其中sizeof(namedButtonStr)
,12sizeof(namedButtonStr[0])
是4,数组的大小是12/4 = 3。
我的问题是,为什么sizeof(namedButtonStr)
12和sizeof(namedButtonStr[0])
4?我的理解是sizeof(namedButtonStr)
3sizeof(namedButtonStr[0])
等于17(“ GLUT_LEFT_BUTTON”有17个字符)。
namedButtonStr[0]
是类型const char*
,因此它sizeof
是指针的大小,而不是它指向的数组。
namedButtonStr
相反,是一个数组,因此它sizeof
是整个数组的字节大小,即3 * sizeof(<one item in the array>)
。
编辑:顺便说一下,这是确定数组大小的一个非常标准的习惯用法,您会经常看到它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句