Reputation: 21
I have been playing around with void pointers and created this example:
#include <stdio.h>
struct intint {
int a;
int b;
};
struct intshortshort {
int a;
short b;
short c;
};
void fill_me(struct intint **pii, void *piss)
{
(void*)*pii = piss; // Question about this line?
}
int main()
{
struct intint *pii = NULL;
struct intshortshort iss;
iss.a = iss.b = iss.c = 13;
fill_me(&pii, &iss);
printf("%d..%d\n", pii->a, pii->b);
return 0;
}
Question:
When I'm using gcc version 2.95.4 everything compiles and works as expected, but gcc version 4.7.3 gives me following error:
void_pointer.c:16:17: error: lvalue required as left operand of assignment
Is there a reason why adding (void *) to lvalue is not allowed anymore?
Edit: Thank you for answers, I think I understood the problem, but the question "why it was ok in the first place?" is still interesting.
Upvotes: 2
Views: 835
Reputation: 10333
The trick is to cast to a void**
and then dereference it:
void fill_me(struct intint **pii, void*piss)
{
*(void **)pii=piss;
}
Output, as expected:
13..851981
13 is obvious
851,981 - 13 = 851,968
851,968 / (256*256) = 13
there are the 2 shorts as an int
Upvotes: 0
Reputation: 2887
The old compiler(old version gcc) may allow cast-as-lvalue, but it ha been removed in the new version, you can find it The cast-as-lvalue, conditional-expression-as-lvalue and compound-expression-as-lvalue extensions, which were deprecated in 3.3.4 and 3.4, have been removed.
Upvotes: 2
Reputation: 529
This question isn't about the void*
, is about typecast and lvalue.
for example:
#include <stdio.h>
int main()
{
int n;
(int)n = 100;
return 0;
}
this code will causes same error: lvalue required as left operand of assignment.
That because the =
operator requires a modifiable-lvalue as its left operand.
So, what is the lvalue
? and what's the modifiable-lvalue
? Please see wikipedia:Value.
Upvotes: 3
Reputation: 213892
It doesn't work for the same reason as why
int x, y;
(int)x = y;
doesn't work. The result of a cast is not a "lvalue", it does not hold a memory location where you can store something inside. Rather regard the result of (int)x
as a temporary, invisible variable, which only exists during the execution of this operation.
Upvotes: 2
Reputation:
You cannot use cast operator on the left operand of the assignment operator in C.
Upvotes: 0