user1128265
user1128265

Reputation: 3049

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.

Upvotes: 7

Views: 12647

Answers (2)

Joseph Quinsey
Joseph Quinsey

Reputation: 9952

You don't mention what compiler you are using. If it is C99-compliant, then the following should work:

   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.


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. See e.g. 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

Upvotes: 5

Luchian Grigore
Luchian Grigore

Reputation: 258548

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

Upvotes: 7

Related Questions