理解C ++中的多维字符串数组

时间:2016-07-24 19:40:20

标签: c++ arrays multidimensional-array

我是c ++的新手。我无法理解为什么以下代码打印“r”字符串。我认为它应该是一个2X3X4元素的数组,所以通过指向arr[0][0][0],我希望第一个字符串中的第一个字符为arr = a,但这会打印{{1} }。谁能解释一下呢?

abcd

修改

令我困惑的是python中的行为。以下python代码打印#include <iostream> using namespace std; int main() { string arr [2] [3] [4]={ {"abcd","efgh","ijkl"}, {"mnop","qrst","xywz"} }; cout<<arr [1] [0] [1] [1]<<endl; return 0; }

a

它会解决第一个列表中第一个字符串的第一个字母。

我认为在c ++中相当于这个:

arr=[["abcd","efgh","ijkl"],["mnop","qrst","xwyz"]]

print arr[0][0][0]

指向第一个数组的第一个字符串中的第一个字母。但这会打印第一个字符串#include <iostream> using namespace std; int main() { string arr [2] [3] [4]={ {"abcd","efgh","ijkl"}, {"mnop","qrst","xywz"} }; cout<<arr[0][0][0]<<endl; return 0; } 。我的问题是为什么我应该放置另一个abcd才能到达[0]

4 个答案:

答案 0 :(得分:8)

您的初始化程序按如下方式填充数组:

arr[0][0][0] = "abcd";
arr[0][0][1] = "efgh";
arr[0][0][2] = "ijkl";
arr[1][0][0] = "mnop";
arr[1][0][1] = "qrst";
arr[1][0][2] = "xywz";

所有其他元素都默认初始化为空字符串。

因此,arr[1][0][1]是包含"qrst"的字符串,arr[1][0][1][1]是该字符串的第二个字符,即'r'

答案 1 :(得分:2)

您已经将标准库string对象与c-string / string文字的概念混淆了,并且您通过避免使用std::前缀来帮助自己。如果我们添加它,它开始变得更有意义:

std::string arr [2] [3] [4]={
  {"abcd","efgh","ijkl"},
  {"mnop","qrst","xywz"}
};

你在这里声明的是一个2 x 3 x 4 std :: string实例的数组。但是你所写的内容看起来像是 think 你在声明字符数组:

char arr [2] [3] [4] = {
  {"abcd","efgh","ijkl"},
  {"mnop","qrst","xywz"}
};

几乎会产生你想要达到的效果 - 在这种情况下arr[0][0][0]确实指向a而不是字符串。

不幸的是,这里的问题是你已经指定了最终尺寸为4,然后为初始化器提供了5个字符的c字符串。记住:

"abcd"

相当于

{ 'a', 'b', 'c', 'd', 0 }

因为c字符串是以空字符结尾的。所以你需要写

char arr [2] [3] [5] = {
  {"abcd","efgh","ijkl"},
  {"mnop","qrst","xywz"}
};

或者,如果你真正想要的是特定的字符数组,而不是以空字符结尾的c字符串:

charr arr[2][3][4] = {
    { { 'a', 'b', 'c', 'd' }, { 'e', 'f', 'g', 'h' }, ...

std::string是一个离散对象,而不是c-string的别名。

#include <iostream>
#include <string>

int main() {
    std::string arr[2][3] = {
        { "abcd", "efgh", "ijkl" },
        { "mnop", "qrst", "wxyz" },  // who needs 'u' or 'v'?
    };

    std::cout << "arr[0][0] = " << arr[0][0] << "\n";
    std::cout << "arr[0][0][0] = " << arr[0][0][0] << "\n";

}

http://ideone.com/JQrDxr

答案 2 :(得分:0)

您初始化的数组可能不是您想要初始化的数组。

一维字符串数组

v

二维字符串数组

n > v > 0

三维字符串数组

string arr [2]= {"abcd","efgh"};

因此,string arr [2][2]= {{"abcd","efgh"}, {"ijkl","mnop"}}; 将输出&#39; x&#39;

答案 3 :(得分:0)

你不能将python与c ++进行比较,因为在python中,列表和字符串几乎相同,而在c ++中则完全不同。在Python中,如果你写

并不重要
arr=[["abcd","efgh","ijkl"],["mnop","qrst","xwyz"]]

arr=[["a","b","c","d","e","f","g","h","i","j","k","l"],
    ["m", "n","o","p","q","r","s","t","x","w","y","z"]]

因为意思相同。在c ++中,它将字符串视为一个&#34;容器&#34;这导致你观察到的行为,它将分配这些&#34;容器&#34;到第一个索引而不是个别字符。你可以做的是

char[2][12] arr = {
                    {"a","b","c","d","e","f","g","h","i","j","k","l"},
                    {"m", "n","o","p","q","r","s","t","x","w","y","z"}
                   };