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 possibly reopened, visit the help center作为指导。
                            
                        
                    
                
                                已关闭8年。
            
                    
谁能帮我解释一下这行的内容

(UserList *) malloc(sizeof(UserList));


我是C世界的新手。我了解的是为Userlist类型分配内存。
如果是这样,为什么定义不只是

Userlist malloc(sizeof(UserList))  ?

最佳答案

这段代码正在做的是为UserList类型的结构分配动态内存。上一个表达式(UserList*)告诉编译器应使用哪种类型来处理malloc返回的值。由于malloc在C语言中是通用的,并且可以返回指向任何类型的指针(在C术语中,void*有效),因此可以告诉编译器您希望该指针指向什么类型。这通常在初始化UserList*类型的变量的情况下发生:

UserList* user_list = (UserList *) malloc(sizeof(UserList));


请注意,获得结果的变量如何是指向正确类型的指针。您可以使用常规的*user_list语法访问此新分配的内存中的指针所指向的结构。

07-24 09:46
查看更多