Thursday 23 May 2019

c - Why is strlen working fine without ''?




As title, I have some question using char* in c. For example, if I write this



char *a = calloc(5, 5);
a[0] = '1';
a[1] = '1';
a[2] = '1';
a[3] = '1';
a[4] = '1';

printf("a = %s, length = %d", a, strlen(a));


and the output is



a = 11111, length = 5


Why is strlen working fine without '\0'? Can someone help me understand?


Answer




calloc(5, 5) allocates and zeroes 25 bytes. You assign the first five of these, but the sixth is still '\0'.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...