Observe the following example code (Microcontroller used: ATtiny84A):
void toggle_output(unsigned char *string)
{
for (unsigned char i = 0; i < sizeof(string) - 3; i++)
{
PORTB ^= (1 << PORTB0);
}
}
toggle_output("test");
I would expect the pin, which is attached to port B0, to toggle 4 times - once for each character in `"test"`; however, what is happening is that I am ending up with an endless loop. The pin is endlessly toggling when it should only toggle 4 times.
I know that the pin is functioning normally, as I am able to set the output statically high or statically low. And I know that If I give the for loop a fixed number of times to loop, it will do so the expected amount of times. For example:
void toggle_output(void)
{
for (unsigned char i = 0; i < 5; i++)
{
PORTB ^= (1 << PORTB0);
}
}
toggle_output();
The above code will cause the pin to toggle 5 times as expected. So for some reason the `sizeof` operator is yielding some enormous number, or the microcontroller is, for some reason, adding to it. What is even stranger, is if I write an equivalent C program on my computer that just prints a number for each character in a string, it does so as expected:
void number_for_character (unsigned char *string)
{
for (i = 0; i < sizeof(string) - 3; i++)
{
printf("1");
}
}
number_for_character("test");
OUTPUT: 1111
What is going on here? Why isn't the `sizeof` operator working with the ATtiny84A?