Reputation: 11
I have a small issue, and I'd like to understand regarding pointers... when compiling I've this error:
error: lvalue required as left operand of assignment
my code is this one :
typedef struct _matrix_info
{
unsigned int matrix[2][5][4];
}matrix_info_t;
static matrix_info_t matrix_custom_policy = {....}
matrix_info_t* matrix_custom_get(void)
{
return &matrix_custom_policy;
}
static matrix_info_t matrix_policy[3] =
{
// Only the first 2 cases are initialized
........
}
main()
{
.....
// the third case is initialized here;
&(matrix_policy[3]) = matrix_custom_get();
}
Do you have an idea why I've this error? Should I do a memcpy instead of ? Thanks in advance.
Upvotes: 1
Views: 62
Reputation: 11
Thank you for your answers and explanations.
Of course, the index was wrong [3], typo error :)
So now I understand, I can't change the address but only the value. The solution from M Ohem works fine and also from Vlad from Moscow by dereferencing the pointer.
Thank you so much.
Upvotes: 0
Reputation: 311068
This expression
&(matrix_policy[3])
creates a temporary object that equivalent to expression
matrix_policy + 3
that in turn is not an lvalue and may not be assigned.
In fact statement
&(matrix_policy[3]) = matrix_custom_get();
may be rewritten like
(matrix_policy +3 ) = matrix_custom_get();
and of course is an invalid statement.
Take into account that you are using wrong index in this statement because the valid range of indices according to the definition of the array
static matrix_info_t matrix_policy[3] =
{
//...
};
is [0, 2]
Do you mean something like the following?
matrix_policy[2] = *matrix_custom_get();
Upvotes: 2
Reputation: 19874
matrix_policy
is an array and address of a array element can't be a modifiable lvalue in C so there is an error.
&(matrix_policy[3]) = matrix_custom_get();
But you can store value in the array like
matrix_policy[3] = <value>;
Upvotes: 0
Reputation: 29126
&
takes the address of a variable. The result is an "rvalue", i.e. a read-only value that can appear on the right-hand side of an assignment. An "lvalue" is something that may appear at the left-hand side of an assignment and can be assigned to. You can't re-assign the address of a variable.
Your matrix_custom_get
returns a pointer to matrix_info_t
. You want to overwrite the contents of a matrix_info_t
with the custom matrix, so you must dereference the pointer you obtained:
matrix_policy[2] = *matrix_custom_get();
Note that you can't access the item at index 3 in an array of three entries, as Anton H has pointed out.
Upvotes: 0
Reputation: 320
in main() function, you are using & operator which will return an address of the variable. object present on left side of assignment operator should be able to hold the value you are assigning. Don't use & with array member as it will represent only address instead of array member.
Upvotes: 1