I spent some time trying to understand what was going on with this code but in the end I couldn't fully figure it out.
void knock_knock(char *s){
while (*s++ != '\0')
printf("Bazinga\n");
}
int main() {
int data[5] = { -1, -3, 256, -4, 0 };
knock_knock((char *) data);
return 0;
}
I was surprised when I saw it didn't print 'Bazinga' 5 times, but 8. My next thought was that it was just iterating over the length of the pointer, so it would make sense that it printed 8 times. But, then I changed the first number of the array from -1, to check whether the data truly was relevant or not, and this is where I was confused. It didn't print 8 times anymore, but just once. Why?
Using the following code
#include<stdio.h>
void knock_knock(char *s)
{
while (*s++ != '\0')
printf("Bazinga\n");
}
int main()
{
int data[5] = { -1, -3, 256, -4, 0 };
printf("%08X - %08X - %08X\n", data[0], data[1], data[2]);
knock_knock((char *) data);
return 0;
}
You can see that HEX values of data
array are
FFFFFFFF - FFFFFFFD - 00000100
Function knock_knock
print Bazinga
until the pointed value is 0x00
due to
while (*s++ != '\0')
But the pointer here is pointing chars, so is pointing a single byte each loop and so, the first 0x00
is reached accessing the "first" byte of third value of array.