Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: String erroneously printing twice

Tags:

c

string

printf

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?

like image 812
HHHH Avatar asked Mar 13 '26 23:03

HHHH


1 Answers

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";
like image 183
jo3rn Avatar answered Mar 16 '26 11:03

jo3rn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!