15

Look at the following piece of code in C++:

char a1[] = {'a','b','c'};
char a2[] = "abc";
cout << sizeof(a1) << endl << sizeof(a2) << endl;

Though sizeof(char) is 1 byte, why does the output show sizeof(a2) as 4 and not 3 (as in case of a1)?

1
  • 1
    +1 Judging from the answers (and my experience with junior programmers), this is a question that causes a lot of confusion and results in many subtle bugs that can be difficult to find. Commented May 24, 2012 at 10:56

3 Answers 3

26

C-strings contain a null terminator, thus adding a character.

Essentially this:

char a2[] = {'a','b','c','\0'};
Sign up to request clarification or add additional context in comments.

1 Comment

I like this answer for its clear statement of equivalence of initialization, but it makes more sense to me to talk about a2, not a1 - the init you cite here is what you get by stuffing the C-String into a2.
3

That's because there's an extra null '\0' character added to the end of the C-string, whereas the first variable, a1 is an array of three seperate characters.

sizeof will tell you the byte size of a variable, but prefer strlen if you want the length of a C-string at runtime.

Comments

0

For a2, this is a string so it also contains the '\n'

Correction, after Ethan & Adam comment, this is not '\n' of course but null terminator which is '\0'

4 Comments

There is no \n (linefeed) at the end of a2. There is a null (\0) character at the end of a string. Shame on you, upvoter.
-1: Wrong, a2 doesn't contain '\n' in the end but rather '\0'.
sorry you are right, i meant the null terminator '\0' thanks for the correction
@miks Adam commented before me. However, I removed the downvote following your correction :)

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.