Reputation: 991
I allocated memory for the r, which is a double pointer to struct. However, When I was trying to use this variable, I got an error which is saying:
read-command.c:461:7: error: lvalue required as left operand of assignment
r+i = postfixToTree(postfix_string, &csPtr->nodeArray[i]);
^
make: *** [read-command.o] Error 1
r+i = postfixToTree(postfix_string, &csPtr->nodeArray[i]);
int b;
struct command** r;
r = (struct command**) malloc(50 * sizeof(struct command*));
for( b=0; b<50; b++){
*(r+b)=(struct command*) malloc(50*sizeof(struct command));
}
How do I assign a value to r?
Upvotes: 1
Views: 7902
Reputation: 177640
Is this what you want? Make sure to include stdlib.h
, the malloc casts are not needed, and *(r+b)
is equivalent to r[b]
.
#include <stdlib.h>
struct command {
int x; // just a definition to compile
};
int main()
{
int b;
struct command** r;
r = malloc(50 * sizeof(struct command*));
for( b=0; b<50; b++) {
r[b] = malloc(50*sizeof(struct command));
}
}
Upvotes: 1
Reputation: 2385
I think you are doing wrong with the pointers.
Do like this,
int b;
struct command** r;
r = (struct command**) malloc(50 * sizeof(struct command*));
for( b=0; b<50; b++){
*(r) + b=(struct command*) malloc(50*sizeof(struct command));
}
Upvotes: 0
Reputation: 10516
General syntax of C assignment.
Lvalue=Rvalue;
Above Rvalue can be result of an expression or function call or simply another variable of same type or constant , Lvalue is a variable that can able to store Rvalue.
r+i = postfixToTree(postfix_string, &csPtr->nodeArray[i]);
^^^
Trying to add i value to r , in the place of Lvalue
.
In C there should not be any evaluation part in The Left hand side.
Add first and then assign
r=r+i; //r+=i;
r = postfixToTree(postfix_string, &csPtr->nodeArray[i]);
you can write above statements As below
r[i] = postfixToTree(postfix_string, &csPtr->nodeArray[i]);
And for every time when you make a call to function postfixToTree()
for( b=0; b<50; b++)
*(r+b)=(struct command*) malloc(50*sizeof(struct command));
Here you are creating 50
copies of struct command
on each iteration
. Doing this leaks lot of memory.
Also free()
the memory which is allocated with the malloc()
inside function.
Upvotes: 2