0
What is the meaning of this c language statement?
int *p; // a pointer p= ( structure *) malloc(4); // suppose structure is defined
1 Réponse
+ 1
First it declares an int pointer p.
Then it calls malloc to allocate 4 bytes on the heap, and assigns the pointer returned by malloc to p. At the same time it casts the returned pointer to 'pointer to structure'.
There are some issues with this code. We don't know the layout of 'structure', but the code implies it is 4 bytes size. The code also implies the 1st member in the structure is an int (since p is an int*), although this would be an unusual way to do it (even though it casts the output of malloc to a 'pointer to structure'). The compiler is going to error on casting this structure* to int*, so this code will not compile.
I suspect the intent is something like this:
structure* p;
p = (structure*)malloc(sizeof(structure));