HHHH
HHHH

Reputation: 101

C: String erroneously printing twice

I'm playing around with C strings as in the following programme:

#include <stdio.h>

int main(void){
    
    char *player1  = "Harry";
    char player2[] = "Rosie";
    char player3[6] = "Ronald";

    printf("%s %s %s\n", player1, player2, player3);
    return 0;
}

Which prints the following:

Harry Rosie RonaldRosie

Why is "Rosie" printing out twice?

Upvotes: 3

Views: 473

Answers (1)

jo3rn
jo3rn

Reputation: 1421

Ronald has 6 letters, so char player3[6] leaves no space for the null-terminator character '\0'.

In your case, it printed whatever comes after Ronald in memory until a '\0' was encountered. That happened to be Rosie. You might not always be so lucky and run into an error (e.g. memory protection) before finding a '\0'.

One solution (apart from how you initialized Harry and Rosie) is to increase the number of elements by one to provide space for a trailing '\0':

char player3[7] = "Ronald";

Upvotes: 7

Related Questions