Why do we need to cast what malloc returns?

后端 未结 7 1865
情歌与酒
情歌与酒 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:34

    You don't. void* will implicitly cast to whatever you need in C. See also the C FAQ on why you would want to explicitly avoid casting malloc's return in C. @Sinan's answer further illustrates why this has been followed inconsistently.

提交回复
热议问题