简体   繁体   English

C ++中的矩形2D字符数组

[英]Rectangular 2D character arrays in C++

I'm using the 2D character arrays for storing multiple strings. 我正在使用2D字符数组存储多个字符串。 The code below works fine & outputs the proper strings. 下面的代码可以正常工作并输出正确的字符串。

    char str[3][4];

    std::cin >> str[0] >> str[1] >> str[2] >> str[3];

    std::cout << str[0] << '\n' << str[1] << '\n' << str[2] << '\n' << str[3];

but when I try this 但是当我尝试这个

    char str[3][3];

    std::cin >> str[0] >> str[1] >> str[2];

    std::cout << str[0] << '\n' << str[1] << '\n' << str[2];

Then, if I input 然后,如果我输入

abc

xyz

pqr

I get the output 我得到了输出

abcxyzpqr

xyzpqr

pqr

What might be the possible explanation? 可能的解释是什么?

The size of your strings is 3 and you are giving 3 characters in input. 字符串的大小为3并且您要输入3个字符。 Which means that it doesn't get the space to store the null character \\0 and therefore can't find the end of the string. 这意味着它没有空间来存储空字符\\0 ,因此找不到字符串的结尾。

The reason is that C strings are null-terminated. 原因是C字符串是空终止的。 This means that they are treated as ending when the first occurrence of a null character ('\\0', value 0) is encountered. 这意味着当第一次遇到空字符('\\ 0',值0)时,它们被视为结束。

When you enter the three-character string "abc" into str[0], this will be represented in memory as {'a','b','c','\\0'}. 当您在str [0]中输入三个字符的字符串“ abc”时,它将在内存中表示为{'a','b','c','\\ 0'}。 Four characters, the last being the null-terminator. 四个字符,最后一个为空终止符。

This null terminator is then overwritten by the following input as str[0] is a 3-char string and thus, the null terminator will be written to str[0][3] which is equivalent to str[1][0]. 然后,此空终止符会被以下输入覆盖,因为str [0]是一个3字符的字符串,因此,空终止符将被写入str [0] [3],它等效于str [1] [0]。

It's because you're allocating 3 char s per string and they are of length 3 - so there's no \\0 at the end of the string. 这是因为您要为每个字符串分配3个char ,并且它们的长度为3-所以字符串的末尾没有\\0 C++ strings should end with a \\0 to mark the end. C ++字符串应以\\0结尾以标记结束。 When 4 char s are allocated, C++ automatically pads each string with a \\0 . 当分配了4个char ,C ++会自动用\\0填充每个字符串。 It's safe to create arrays of at least n+1 char s when you need to store at most n char s in that. 当您需要在其中存储最多n char时,创建至少n+1 char的数组是安全的。

It seems that the total 9 char s of str are contiguous, so the first string is of length 9. The cout statement goes to print from str[0][0] , and as there's no \\0 at the end of str[0] , it continues printing str[1] and str[2] . 看来str的总共9个char是连续的,因此第一个字符串的长度为cout语句从str[0][0]打印,因为str[0][0]的末尾没有\\0 str[0] ,它将继续打印str[1]str[2]

These strings are named '0-terminated', because a literal string, in C, is a sequence of characters terminated by a 0 (null byte). 这些字符串被命名为“ 0终止”,因为C中的原义字符串是由0(空字节)终止的字符序列。

You are overflowing the terminator with the first character of the successive string. 您正在使用连续字符串的第一个字符使终止符溢出。

Beware to undefined behaviour. 当心未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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