1

This code is producing the strange output below. I tried increasing the character array to be 13 and it printed the whole string, but still had the strange characters at the end. I'm using MinGW on Windows. Could that be the cause?

#include <stdio.h> #include <string.h> int main() { char message[10]; int count, i; strcpy(message, "Hello, world!"); printf("Repeat how many times? "); scanf("%d", &count); for(i=0; i < count; i++) printf("%3d - %s\n", i, message); if(i==count) getch(); } 

enter image description here

3 Answers 3

5

This is because you have to give it one more space, like this:

char message[14]; //^^ See here 13 from 'Hello, world!' + 1 to determinate the string with a '\0' 

It also has to have room to save a '\0' to determinate the string

Also don't forgot to include

#include <string.h> //For 'strcpy()' #include <conio.h> //For 'getch()' 

Example output:

Repeat how many times? 5 0 - Hello, world! 1 - Hello, world! 2 - Hello, world! 3 - Hello, world! 4 - Hello, world! 
Sign up to request clarification or add additional context in comments.

Comments

1

13 is still not enough, because the string had to contain a null character at the end. Furthermore, always make sure the string ends with the null character, '\0'.

Edit: The answer provided by Rizier123 is the most complete.

Comments

0

You're not leaving room for the terminating \0 at the end of the string and thus the printing is printing the message then the value of count as a char.

Always make sure that you allow enough for the string length + 1!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.