简体   繁体   中英

Why do these two char arrays return different results?

I just assigned an ip to a char array and printed it to make sure it was right and got the following results:

int
main(void)
{
    char ip [11] = "65.55.57.27";
    printf(ip);
    return 0;
}

I get

65.55.57.270 "

But if I increase the array size to 12

int
main(void)
{
    char ip [12] = "65.55.57.27";
    printf(ip);
    return 0;
}

I get

65.55.57.27

Can anyone explain this? Why is it that the array of size 11 return a 13 char result while the array of size 12 returns a 11 char result?

The array in

char ip [11] = "65.55.57.27";

has no space for the NUL terminator since the string literal is exactly 11 characters long.

This results in

printf(ip);

having undefined behaviour .

Either of the following would fix the problem:

char ip [12] = "65.55.57.27";
char ip [] = "65.55.57.27";

You made space for 11 bytes but there also exists the implicit null byte \\0 in your char array:

>> ip

   {'6', '5', '.', '5', '5', '.', '5', '7', '.', '2', '7', '\0'}

Hence your array has 12 elements in it, 1 too many for the size. You should have gotten an error on your compiler. This is what I got:

error: initializer-string for char array is too long

I don't like to deal with these trivial problems; that's why I use std::string :

#include <string>
#include <iostream>

int main()
{
    std::string str = "65.55.57.27";

    std::cout << str;
}

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM