Let's conceptualize correctly. Variables are placeholders to store something. Just this, nothing more than reserved in some way.
This variable will store 4 bytes in memory. If the intention is to have a default C string, then it can be up to 3 characters long and will have a terminator at the end, which is the character 0
, also called null and commonly represented by 'strlen()
'
.
In this case we know the size of it during development. And note that nothing guarantees that the string will be properly formed. Nothing guarantees that it will only have these 3 characters. What effectively determines the size of the string is the terminator. So if you create 10 characters and then put the final null will work and functions dealing with strings will assume you have 10 characters.
There you can ask how it puts 10 characters where it was reserved for 3. This is a huge mistake. But language leaves. It is the programmer's problem to turn around and do it right. In that case the content will invade the space of another variable will produce result at the least strange, possibly disastrous and unsafe.
The function normally used to determine the effective size of a string in C, and this is one of the major defects of the language, is the function string
that counts all characters until you find the null terminator.
This can be seen in:
#include <stdio.h>
#include <string.h>
int main() {
char ch[4];
strcpy(ch, "abc");
printf("ch tem %d bytes\n", sizeof(ch));
printf("ch conta com %d caracteres\n", strlen(ch));
strcpy(ch, "texto longo");
printf("ch conta com %d caracteres\n", strlen(ch));
}
See running on CodingGround or CppShell .
Note that in C ++ it is usually more appropriate to use %code% . It has some disadvantages and several advantages. Another form should only be used if there is good justification.