简体   繁体   English

在C中使用硬编码值创建字符串数组

[英]Creating Array of Strings with hard coded value in C

I have created the array of string with hard-coded values as below : 我创建了具有以下硬编码值的字符串数组:

char dev_string[3][3][15] = {{"item01","item02","item03"},
                                 {"item11","item12","item13"},
                                 {"item21","item22","item23"},
                      };

int main()
{

   printf("string 00 = %s \n",dev_string[0][0]);
   printf("string 01 = %s \n",dev_string[0][1]);
   printf("string 02 = %s \n",dev_string[0][2]);


   printf("string 10 = %s \n",dev_string[1][0]);
   printf("string 11 = %s \n",dev_string[1][1]);
   printf("string 22 = %s \n",dev_string[1][2]);


   printf("string 20 = %s \n",dev_string[2][0]);
   printf("string 21 = %s \n",dev_string[2][1]);
   printf("string 22 = %s \n",dev_string[2][2]);

    return 0;
}

Aim is to create a dictionary in C at the end.Instead of hard-coding i want a pointer based implementation because in future I have to keep adding the items to this string. 目的是最后在C语言中创建一个字典,而不是硬编码,我想要一个基于指针的实现,因为将来我必须继续将项目添加到此字符串中。 More over I want to access these strings using some index, which I think I can by providing the row number(0,1 or 2). 此外,我想使用一些索引来访问这些字符串,我认为可以通过提供行号(0、1或2)来访问这些字符串。 I am not getting the right way to do it with pointers.What will be other convenient way to do it with pointers ( single or pointer to two dimension?) 我没有找到正确的方法来使用指针,还有什么方便的方法可以使用指针(单一或指向二维的指针?)

char (*sensor_string)[3][3];

for (int i=0; i < 3; ++i) {
    for (int j=0; j < 3; ++j) {
        sensor_string[i][j] = malloc(sizeof(*sensor_string[i][j]) * (strlen("item") + 3));
        strcpy(sensor_string[i][j], "item");
        char* num = malloc(sizeof(*num) * 3);
        sprintf(num, "%d", (i*3 + j + 1));
        strcat(sensor_string[i][j], num);
    }
}

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

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