C中结构中的字符串数组

use*_*265 2 c arrays string struct

说我们有,

typedef struct{
    char* ename;
    char** pname;
}Ext;

Ext ext[5];
Run Code Online (Sandbox Code Playgroud)

我想要做的是填充数据如下:

ext[0].ename="XXXX";
ext[0].pname={"A", "B", "C"};  // and so on for the rest of the array
Run Code Online (Sandbox Code Playgroud)

- 我很确定这不是正确的做法,因为我遇到了错误.请告诉我正确的方法.谢谢.

Luc*_*ore 5

第一项任务是正确的.

第二个不是.您需要动态分配数组:

ext[0].pname = malloc( sizeof(char*) * 5 );
ext[0].pname[0] = "A";
ext[0].pname[1] = "B";
//and so on
//you can use a loop for this
Run Code Online (Sandbox Code Playgroud)


Jos*_*sey 5

你没有提到你正在使用什么编译器。如果它符合 C99 标准,则以下内容应该有效:

   const char *a[] = {"A", "B", "C"}; // no cast needed here
   const char **b;
   void foo(void) {
       b = (const char *[]){"A", "B", "C"}; // cast needed
   }
Run Code Online (Sandbox Code Playgroud)

您的数组位于 typedef 结构中与这里无关。


编辑:(九年后)。我的答案是错误的:复合文字 infoo()是在堆栈上创建的(也称为自动存储),因此上面的代码是不正确的。例如,请参阅引用的复合数组文字的生命周期,并请参阅使用复合文字初始化变量

相比之下,这个代码片段就很好:

   const char *a[] = {"A", "B", "C"}; // no cast needed here
   const char **b = (const char *[]){"A", "B", "C"}; // cast needed
Run Code Online (Sandbox Code Playgroud)