Let’s conceptualize correctly. Variables are spaces reserved to store something. Just that, nothing more than reserved somehow.
This variable will store 4 bytes in memory. If the intention is to have a string standard of C, so it can have up to 3 characters and will have at the end a terminator, which is the character 0
, also called null and commonly represented by '\0'
.
In this case we know the size of it during development. And note that there is no guarantee that the string will be formed correctly. Nothing guarantees that it will have only these 3 characters. Which effectively determines the size of the string is the terminator. So creating 10 characters and then putting the final null will work and functions that deal with strings will consider it to have 10 characters.
Then you can ask how he puts 10 characters where it was reserved for 3. That’s a huge mistake. But the language leaves. It’s the programmer’s problem to get it right. In this case the content will invade the space of another variable if it produces at least strange results, possibly disastrous and insecure.
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 strlen()
which counts all characters until the terminator is null.
This can be observed 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));
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Note that in C++ it is usually more appropriate to use the type string
. It has some disadvantages and several advantages. Another way should only be used if there is good justification.
"Sizeof" is an operator, not a function. Assuming an "x" variable, "sizeof x" compiles normally. When it is applied to a type ("sizeof(int)") the parentheses are required, probably for syntactic reasons, not because sizeof is a function. http://en.cppreference.com/w/cpp/language/sizeof
– zentrunix
@Joséx., I edited the reply. Thank you for the remark =)
– Taisbevalle