#include <stdio.h>
int main(void) {
char strp[] = "hello";
char strq[] = " world";
strcat(strp,strq);
puts(strp); //hello world
printf("%d",sizeof(strp)-1);//this gives 5(length of 'hello' -1 for '\0')
printf("%d",strlen(strp));//gives correct answer(11)
return 0;
}
Why does sizeof give wrong answer but strlen give right answer in this case?
strcat(strp,strq);invokes undefined bahaviour asstrpis not large enough to accommodate the concatenated string. The result of this operation cannot be predicted.Never ever use
sizeofto get string length.sizeof(x)is giving you the size of in bytesx.Try the same with
char strp[100] = "hello";ALWAYS use
strlenprintf("%d", ...(both) invoke undefined behaviour as you use the wrong format. It has to be%zufor typesize_tThis program demonstrated the difference between
strlenandsizeof:result: