Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof string array in C++

Tags:

c++

arrays

c

sizeof

I am confused about the sizeof string array in C++, I have the following string array:

static const char* namedButtonStr[] = {
        "GLUT_LEFT_BUTTON",
        "GLUT_MIDDLE_BUTTON",
        "GLUT_RIGHT_BUTTON"
};

And to get the size of this array, the following code is used:

int size = int(sizeof(namedButtonStr)/sizeof(namedButtonStr[0]));

Where sizeof(namedButtonStr) is 12, sizeof(namedButtonStr[0]) is 4, and the size of the array is 12/4 = 3.

My question is, why sizeof(namedButtonStr) is 12 and sizeof(namedButtonStr[0]) is 4? My understanding is sizeof(namedButtonStr) is 3 and sizeof(namedButtonStr[0]) is 17 ("GLUT_LEFT_BUTTON" has 17 characters).

like image 785
Tom Avatar asked Nov 30 '25 07:11

Tom


2 Answers

namedButtonStr[0] is of type const char*, so its sizeof is the size of pointer, not the array it points to.

namedButtonStr, on the contrary, is an array, so its sizeof is the bytesize of the whole array, that is, 3 * sizeof(<one item in the array>).


Edit: By the way, this is a pretty standard idiom for determining array's size, you'll see it often.

like image 62
Vlad Avatar answered Dec 01 '25 19:12

Vlad


My question is, why sizeof(namedButtonStr) is 12 and sizeof(namedButtonStr[0]) is 4? My understanding is sizeof(namedButtonStr) is 3 and sizeof(namedButtonStr[0]) is 17 ("GLUT_LEFT_BUTTON" has 17 characters).

The namedButtonStr will contain 3 pointers. (In general, a C pointer is 4 bytes, this may change as 64 bit busses become common, along with 64 bit compilers.)

So, 3 pointers * 4 (bytes per pointer) = 12 bytes.

The namedButtonStr[0] refers to a single/first one of those 3 pointers, and as stated above, each pointer is 4 bytes.

The result is 12/4 = 3

like image 29
user3629249 Avatar answered Dec 01 '25 20:12

user3629249