2

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).

9
  • 1
    If you're writing C++, why not write real C++, and use something like: std::vector<std::string> namedButtons = {"GLUT_LEFT_BUTTON", "GLUT_MIDDLE_BUTTON", "GLUT_RIGHT_BUTTON"};. In this case, the number of strings is just namedButtons.size(). Commented Nov 11, 2014 at 22:25
  • 2
    namedButtons is an array of pointers, not an array of strings. Each element points to the first character of a string. Commented Nov 11, 2014 at 22:27
  • @Hi, I'm new to c++, I'm learning OpenGL, this code came from my teacher, there must be some reason he created the string array like that, can you explain it? Commented Nov 11, 2014 at 22:28
  • 1
    @Tom - You will be surprised at the amount of bad "teacher code" that shows up every day here. Commented Nov 11, 2014 at 22:32
  • what is actually created is an array of 3 string pointers, where each pointer points to a string. The string(s) location is in the .rodata, so the actual strings cannot be changed. Commented Nov 11, 2014 at 22:38

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.