Storing a string in an array of chars without the null character

前端 未结 4 1083
走了就别回头了
走了就别回头了 2021-01-14 10:07

I\'m reading the C++ Primer Plus by Stephen Prata. He gives this example:

char dog[8] = { \'b\', \'e\', \'a\', \'u\', \'x\', \' \', \'I\', \'I\'}; // not a s         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 10:23

    It looks like your C++ compiler is allocating space in 4-byte chunks, so that every object has an address that is a multiple of 4 (the hex addresses in your dump are divisible by 4). Compilers like to do this because they like to make sure larger datatypes such as intand float (4 bytes wide) are aligned to 4-byte boundaries. Compilers like to do this because some kinds of computer hardware take longer to load/move/store unaligned int and float values.

    In your first example, each array need 8 bytes of memory - a char fills a single byte - so the compiler allocates exactly 8 bytes. In the second example each array is 3 bytes, so the compiler allocates 4 bytes, fills the first 3 bytes with your data, and leaves the 4th byte unused.

    Now in this second case it appears the unused byte was filled with a null which explains why cout stopped at the end of the string. But as others have pointed out, you cannot depend on unused bytes to be initialized to any particular value, so the behaviour of the program cannot be guaranteed.

    If you change your sample arrays to have 4 bytes the program will behave as in the first example.

提交回复
热议问题