开发者

Can't understand what this code do [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and poss开发者_高级运维ibly reopened, visit the help center for guidance. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜