Extra characters appended to end of line in c

So, I am trying to print a string in C and I keep getting extra characters at the end of the string when I print it. Code:

char binaryNumber[16] = "1111000011110000";
printf("binary integer: %s\n", binaryNumber);

      

Output:

binary integer: 1111000011110000▒▒▒▒

Could you please help me figure out why this is happening. I think this is the root of some other problems in my code. I used to have this problem when I created a string in a more complex way and in this case I also got extra characters, but they were different. So I made the line in the most straightforward way (method shown here) and I still face the problem

+3


source to share


3 answers


It should be

char binaryNumber[17] = "1111000011110000";

      



This is because strings in C are null terminated. This way you will be reading garbage unless you provide extra character space for the implicit \0

to be added

+3


source


Let the compiler figure out the number of items needed



char binaryNumber[] = "1111000011110000";
// same as
// char binaryNumber[17] = "1111000011110000";

      

+6


source


You have 16 characters in your array. and there is no place to store the symbol \0

.

%s

prints a string until it encounters \0

So you can see that some printable characters are being printed. Please make your line \0

complete

+2


source







All Articles