5

If I have for example the following array declaration: int a[5];, this means that I have an array "a" that holds 5 integer variables.

Wouldn't it be in memory something like this (See the \0)?


|0|1|2|3|4|\0|

So, in this case, do I still say that a[] is of size 5 or should I say it is of size 6?

And, if I copy it to the array: int b[4] what will happen in this case? What will happen to the integer variable in location 4 of a[], will it overwrite \0?

Thanks.

3 Answers 3

14

Arrays are not, in general, automatically zero-terminated. C strings are zero-terminated, but this is not a C string.

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

9 Comments

@David Heffernan. Thanks for your reply. Just to confirm, "\0" means a new line, is that right?
It is also worth mentioning that when declaring a C string, space for the zero terminator has to be reserved explicitly. That is, char s[11]; for a 10-byte string.
@aali, a new line is '\n' or maybe "\r\n" or '\r' depending on the platform. '\0' is just a zero byte (it doesn't represent any printable character).
@aali, \0 means end of sequence in memory. That's something completely different compared to \n.
@aali: No, '\0' is the null character, not a new line. (Also, "\0", is a C null terminated string that contains two null characters the explicitly typed one, and the implicitly added by the compiler at the end of the literal, which is different from '\0'). I recommend that you take a nice introductory book on C++ and work from there on.
|
6

There are only |0|1|2|3|4| in the memory, not the sixth one. So the size is 5.

Comments

2

Great explanation of arrays for beginners.

Comments

Your Answer

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