carrayscharsymbiancarbide

showing extra data in array values


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";