typedef struct _DListNode
{
struct _DListNode* prev;
struct _DListNode* next;
void* data;
}DListNode;
in gcc :
DListNode *p = NULL;
p = (DListNode*)malloc(sizeof(DListNode));
p->data = (int*)malloc(sizeof(int));
scanf("%d", (int*)p->data);
compile correctly.
in gcc :
DListNode *p = NULL;
p = (DListNode*)malloc(sizeof(DListNode));
(int*)p->data = (int*)malloc(sizeof(int));
scanf("%d", (int*)p->data);
There is a problem on :
(int*)p->data = (int*)malloc(sizeof(int)); -------error: lvalue required as left operand of assignment.
the difference:
scanf("%d", (int*)p->data) ,
(int*)p->data = (int*)malloc(sizeof(int)),
p->data = (int*)malloc(sizeof(int));
How about
(int*&)p->data = (int*)malloc(sizeof(int));“?(int *) gives the pointer value itself, i.e. it’s akin to saying
0x12345678 = malloc(sizeof(int));.Btw, mallocing for something as small as an int is extremely wasteful.
EDIT:
This might only work in C++, not C.
Why do you cast in the first place? You’re assigning a void pointer to a void pointer. Isn’t that convenient? Why cast?
If you really want to amuse yourself, you could do something silly like
*(int **) &(p->data) = (int *) malloc(sizeof(int));. Nonsense, right? Right. Just assign the value. Better yet, replace your data with a union.