showing extra data in array values
Question
I am using this part of c code in carbide c/c++
char c1[]={0x01};
char c2[]={0x02};
char* c [] = {c1,c2};
when i check values of c[0],c[1].. i am seeing two values like this in debug mode
c[0] = \x01\x01 & (x) = *[0] = \x01
c[1] = \x02\x01\x01 & (x) = *[1] = \x02
and if i calculate length like this
int cclen2 = strlen(c[0]);
getting cclen2 = 2; but i should get values as 1.
Solution
c1
and c2
do not have null terminators, and strlen()
requires a null terminator (along with many other C string handling functions, like printf("%s", c1)
for example). A null terminator is only implicitly added when a string literal is used to initialise the char[]
.
Change to either:
char c1[] = { 0x01, 0x00 };
char c2[] = { 0x02, 0x00 };
or:
char c1[] = "\x01";
char c2[] = "\x02";
OTHER TIPS
Array creates a special type of constant pointer. if you declare this as char then at last a null character is added. actually your c[0] statement is replaced by *(c+0); and get the address c.
strlen(c[0]) is replaced by strlen(c); and you got full length of string till null character.
i think this is enough explanation.