Can't understand what this code do [closed]
Can anyone help me with explanation what this line do
(UserList *) malloc(sizeof(UserList));
I'm new to C world. What I understand is that allocate memory for Userlist type. If so why definition is not just
Userlist malloc(sizeof(UserList)) ?
What this code is doing is allocating dynamic memory for a structure of type UserList
. The previous expression, (UserList*)
tells the compiler of what type to treat that value returned by malloc
. As malloc
is generic in C and can return a pointer to any type (effectively in C terminology, void*
), you can tell the compiler what type do you expect this pointer points to. This usually happens in the context of an initialization of a variable of type UserList*
:
UserList* user_list = (UserList *) malloc(sizeof(UserList));
Note how the variable getting the result is a pointer to the correct type. You can access to the structure pointed by the pointer in this new allocated memory using the normal *user_list
syntax.
malloc returns a pointer (memory location) to the memory allocated. The * means a "pointer to" a UserList rather than the userlist itself.
I'm not sure if this line is a declaration or a statement. If it's a statement then the brackets cause the type of the pointer returned to be cast to "pointer to UserList" rather than "void *" meaning pointer to anything.
精彩评论