如何存储2个char数组的数组?

时间:2016-02-04 20:27:01

标签: c arrays 2d

我想拥有一个存储2个项目的数组,所以这是最好的方法吗?

char array[5][2]= {{"data1","1"},
                {"data2","2"},
                {"data3","3"},
                {"data4","4"},
                {"data5","5"}};

如何在“data2”,“2”中存储内容?

4 个答案:

答案 0 :(得分:1)

2D char数组在这里不起作用,但是一个struct数组可以满足你的需要:

    struct string_pairs
    {
        char str1[10];
        char str2[10];
    } array[] = {{"data1","x"},
                {"data2","x"},
                {"data3","x"},
                {"data4","x"},
                {"data5","x"}};

答案 1 :(得分:1)

char

的数组
char arr1[6] = "data1";               // 1D array

char

的数组数组
char arr2[2][6] = { {"data1"},        // 2D array
                    {"1"}      };   

char

数组的数组
char arr3[5][2][6] = {{"data1","1"},  // 3D array
                      {"data2","2"},
                      {"data3","3"},
                      {"data4","4"},
                      {"data5","5"}};  

"dataX","X"分配给数组的第二个元素

strcpy(arr[1][0], "dataX");
strcpy(arr[1][1], "X");  

答案 2 :(得分:0)

您可以将其设为2d char*数组

char *array[5][2]= {{"data1","1"},
                   {"data2","2"},
                   {"data3","3"},
                   {"data4","4"},
                   {"data5","5"}};

然后要更改字符串数据,您只需访问各个组件(编辑{"data2","2"}):

array[1][0] = "words", array[1][1] = "a";

基本上,当您使用第一组方括号array[1],访问行{"data2","2"},然后使用第二组方括号时,您正在访问行内部的组件。因此,array[1][0]最初为"data2"array[1][1]最初为"2"。就像array[2][0] "data3"array[2][1] "3"一样。

答案 3 :(得分:-1)

我认为这是结构的典型任务。 在我看来,这应该有效:

struct strings  // definition of a struct calld strings
{
char[] a;
char[] b;
}

struct strings arrayofstrings[n];  // instancing an array of structs

arrayofstrings[i].a = {"data"};  // reference to the element "a" of the i-part of the array
arrayofstrings[i].b = {"1"};

你可以创建n个结构实例"字符串"