rofls
rofls

Reputation: 5115

What is causing this strange output from the printf command in c, and how do I stop it from happening?

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

Upvotes: 1

Views: 210

Answers (3)

engrmat
engrmat

Reputation: 31

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.

Upvotes: 1

Gwyn Evans
Gwyn Evans

Reputation: 1521

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!

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

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!

Upvotes: 5

Related Questions