Compiler error (lvalue required as left operand of assignment) when using malloc

MattSt picture MattSt · Mar 30, 2014 · Viewed 11.4k times · Source

I got 2 structs,a pointer to each struct and a void **stack which points to the pointers of the structs.

my problem is at the line

(*ptr2+*a)=(struct student *)malloc(sizeof(struct student));

*a is a variable that increases by 1 everytime a stud registration happens so i don't allocate memory for the same address over and over again

since i send the address of stud(&stud) at the menu function and then at the input function

*ptr2==stud 

thus

stud[*a]== *(stud+*a)== *(*ptr2+*a)

why is (*ptr2+*a) on the left side of malloc wrong? part of the code

struct student
{
    char flag;
    char surname[256];
    int semester;
};

main()
{
    ...
    struct student *stud;
    menu(stack,stackcopy,reversedstack,&prof,&stud,stacksize,&head);
    ...
}

void menu(void **stack,void **stackcopy,void **reversed,struct professor **ptr1,struct student **ptr2,int size,int *head)
{
    ...
    input(stack,ptr1,ptr2,size,head,&a,&b);
    ...
}


int input(void **stack,struct professor **ptr1,struct student **ptr2,int size,int *head,int *a,int *b)
{
            ...
            done=Push(stack,head,(*(int *)ptr2+*a),size);
            (*ptr2+*a)=(struct student *)malloc(sizeof(struct student));
            stud_input(ptr2,a);
            ...
}

Answer

Joker_vD picture Joker_vD · Mar 30, 2014

It's wrong because you need (roughly) a variable on the left side of the assignment, not a value. You can't write 1 = 2;, but you can write int a; a = 1;. By the same logic, you can't write &a = (void*)0;.

Dereferencing a pointer gives you a variable, so you can write struct student *z = &a; *z = b;.

If you want to write stud[*a] = malloc(...);, but you don't have stud, only ptr2, for which *ptr2 == stud holds, the correct way is, obviously,

(*ptr2)[*a] = malloc(...);

And (*ptr2)[*a] == *(*ptr2 + *a), so this would work as well:

*(*ptr2+*a) = malloc(sizeof(struct student));