Why do we need to cast what malloc returns?

后端 未结 7 1871
情歌与酒
情歌与酒 2020-12-10 18:04
    int length = strlen(src);
    char *structSpace = malloc(sizeof(String) + length + 1);
    String *string = (String*) structSpace;    
    int *string = (int*) s         


        
7条回答
  •  醉话见心
    2020-12-10 18:24

    Because malloc returns a pointer to void, i.e., it is simply allocating chunks of memory with no regard as to the data that will be stored there. In C++ your returned void* will not be implicitly cast to the pointer of your type. In your example, you have not cast what malloc has returned. Malloc returned a void* which was implicitly cast to a char*, but on the next line you... ok, it doesn't make much sense anymore.

提交回复
热议问题