7

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.

2
  • 2
    Is this homework? If so, you should tag it as such. Commented Mar 1, 2012 at 19:22
  • Also, are you trying to statically allocate a large number of such structs? Commented Mar 1, 2012 at 19:24

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

5

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

2 Comments

This was exactly what I was looking for. Thanks for saving me some headache.
why is the cast needed in this case?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.