简体   繁体   English

C中结构中的字符串数组

[英]array of strings within a struct in C

Say we have,说我们有,

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

Ext ext[5];

What I am trying to do is to populate the data as following:我想要做的是填充数据如下:

ext[0].ename="XXXX";
ext[0].pname={"A", "B", "C"};  // and so on for the rest of the array

-- I am pretty sure this is not the right way of doing this because I am getting errors. -- 我很确定这不是正确的做法,因为我遇到了错误。 Please let me know the correct way to do this.请让我知道执行此操作的正确方法。 Thanks.谢谢。

The first assignment is correct.第一个任务是正确的。

The second one is not.第二个不是。 You need to dynamically allocate the array:您需要动态分配数组:

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

You don't mention what compiler you are using.你没有提到你使用的是什么编译器。 If it is C99-compliant, then the following should work:如果它是 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
   }

Your arrays being within a typedef'd struct is irrelevant here.您的数组在 typedef 结构中与此处无关。


Edit: (nine years later).编辑:(九年后)。 My answer is wrong: the compound literal in foo() is created on the stack (aka automatic storage), and so the above code is incorrect.我的答案是错误的: foo()的复合字面量是在堆栈上创建的(又名自动存储),因此上面的代码是不正确的。 See eg Lifetime of referenced compound array literals , and see Initializing variables with a compound literal .参见例如引用复合数组文字的生命周期,并参见使用复合文字初始化变量

In contrast, this code snippet is fine:相比之下,这个代码片段很好:

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

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

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