Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 248
user1128265 Avatar asked Dec 28 '22 05:12

user1128265


2 Answers

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
like image 172
Luchian Grigore Avatar answered Dec 30 '22 10:12

Luchian Grigore


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
like image 31
Joseph Quinsey Avatar answered Dec 30 '22 10:12

Joseph Quinsey