Jessica Melia
Jessica Melia

Reputation: 9

error in allocating pointer to array of struct

I'm trying to allocate memory for pointer to array of struct, however it give me a weird error. here's the code:

struct command{
    int type;
    char* input;
    char* output;
    struct command *command[2];
}

when I try to allocate memory for the array size 2, I try:

temp->command = (command*)malloc(sizeof(struct command[2]));

However, I got this error:

incompatible types when assigning to type âstruct command *[2]â from type âstruct command *â

any suggestion?

Upvotes: 0

Views: 136

Answers (3)

Eric Bond
Eric Bond

Reputation: 1

If you want the element to be a pointer to an array of struct then you can declare and allocate like this...

struct command (*command)[2]; /* note the parentheses */

temp->command = malloc(sizeof *temp->command);

... and if you want the element to be an array of pointers then you can do something like this:

struct command *command[2]; /* equivalent to *(command[2]) */

temp->command[0] = malloc(sizeof *temp->command[0]);
temp->command[1] = malloc(sizeof *temp->command[1]);

(Note that a good way to determine "array of pointer" vs. "pointer to array" is to work your way outwards from the variable name, guided by operator precedence and associativity rules. For example if your declaration is "sometype *myvar[2]" you would start with "myvar is an array of ..." rather than "myvar is a pointer to..." because [] has a higher precedence than *.)

The error message was because your cast indicated type->command was a pointer to struct, which was a conflict since you declared it as an array of pointers to struct. However you shouldn't need to cast unless you are using a C++ compiler.

Upvotes: 0

John Bode
John Bode

Reputation: 123596

You've declared command as a 2-element array of pointer to type struct command, so you don't need to allocate memory for the array, just for each array element, like so:

temp->command[i] = malloc( sizeof *temp->command[i] );

Upvotes: 3

Chinna
Chinna

Reputation: 4002

You need to do like this

for(i=0;i<2;i++)
   temp->command[i] = malloc(sizeof(struct command[i]));

Upvotes: 1

Related Questions