Search code examples
carraysstringprintfinitializer

printf in C with strings that has shorter initializer behaves weird


So I tried to make character arrays and play around with it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char ** argv) {

    char str1[11] = "Yo! Angelo!~";  //total length of 12, initializer is shorter
    char str2[14] = "Yo! Angelo!233"; //total length of 14, initializer is same length
    char str3[60] = "Yo! Angelo!wwww"; //initializer is longer

    printf("%s"\n, str1);

}

the compiler gives me the warning that initializer-string for array of chars is too long

I expected that it will only give me the first 11 characters of str1, which is Yo! Angelo! without '~'

but this is I got all three arrays in a line (first one is first 11 chars) as this

Yo! Angelo!Yo! Angelo!233Yo! Angelo!wwww (all three strings smashed together without space)

the same problem still exist when I changed the initializer to length of 12 (same length as the string)

also, when I try printf("%s\n", str2), it has similar problem -- it prints second and third string in one line without anything in between

but when I change it to 13 or larger, it only prints str1, as intended.

It's not emergency and I know I must have the string declared longer than its length (longer than 13 in this case) but I just wonder why does printf do funky things like this.

Thank you~


Solution

  • When you use a string initializer that is too long for the array, you lose the trailing characters, including the trailing NUL terminator. So you end up with arrays (str1 and str2) that don't contain strings (no NUL terminator), so when you try to print it as a string, you get undefined behavior. Specifically, it prints whatever happens to follow the array in memory, which turns out to be the other arrays.