bs7280
bs7280

Reputation: 1094

Extra characters added to end of string in c

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

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

Output:

binary integer: 1111000011110000▒▒▒▒

can you please help me figure out why this is happening. I think this is the root of some other problems in my code. I had this problem before when I was creating the string in a more complex way, and got extra characters in that case too, but they were different. So I made a string the most basic way possible (method shown here) and am still getting the problem

Upvotes: 4

Views: 14513

Answers (3)

Gopi
Gopi

Reputation: 19864

You have 16 characters in your array. and there is no place to hold a \0 character.

%s prints a string until it encounters a \0

So what you are seeing is some garbage characters being printed out.Please make your string is \0 terminated

Upvotes: 3

Bhargav Rao
Bhargav Rao

Reputation: 52071

It should be

char binaryNumber[17] = "1111000011110000";

This is because strings in C are null terminated. So you will be reading garbage if you don't give an extra character space for the implicit \0 which will be added

Upvotes: 5

pmg
pmg

Reputation: 108978

Let the compiler determine the amount of elements needed

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

Upvotes: 6

Related Questions