Reputation: 11
In the following code, fizz prints correctly, but buzz does not. What is wrong with using a char array here or in what way am I using it wrong?
#include <stdio.h>
int main() {
int i;
char *fizz = "fizz";
char buzz[4] = "buzz";
for(i = 1; i <= 100; i++) {
if(!((i %3 == 0) || (i%5 == 0)))
printf("%d", i);
if(i%3 == 0)
printf("%s", fizz);
if(i%5 == 0)
printf("%s", buzz);
printf("\n");
}
}
Upvotes: 0
Views: 91
Reputation: 734
You have declared the size of the buzz array as 4 and including \0
the size of the string is 5. so you have to change the size of the buzz array as 5 or don't mention the size.
char buzz[5] = "buzz";
because buzz is not a pointer variable, if the buzz is a pointer variable it will allocate the memory according to the string, so there is no need to specify the size.
As buzz is a array you have to mention the size correctly.
And while printing we use %s
, %s
will print the string till the \0 character occurs.
In the buzz string there is no \0 character, this is the problem.
Upvotes: 3
Reputation: 121
buzz contains 4 character, it has no space reserved for the null character, therefore it cannot be printed correctly with %s. %s specifies that a null terminated string to be printed and it cannot work correctly if the string is not null terminated.
Change your initialization to char buzz[] = "buzz"
Upvotes: 2
Reputation: 141574
The %s
specifier prints a string. A string is a series of characters followed by a null-terminator. To put it another way, you tell printf
where your characters start, and printf
keeps printing until it encounters a null terminator.
The "buzz"
expression is a null-terminated string, however you shoe-horned it into char buzz[4]
so the null terminator didn't fit. The result is that the buzz
array does not contain a null terminator, and so printf
reads off the end of the string, causing undefined behaviour. To fix this write:
char buzz[] = "buzz";
which will include a null terminator and allocate the right amount of space.
Upvotes: 3
Reputation: 43842
Neither string is actually four bytes long. C strings are NUL-terminated, so they're always their length in characters plus one for the '\0'
character. Therefore, you should change the declaration of buzz
as follows:
char buzz[5] = "buzz";
However, also note that explicitly declaring the variable's length when initializing with a string literal is not required. You can just leave out the number, and it will work fine.
char buzz[] = "buzz";
Upvotes: 6