Why do you specify the size when using malloc in C?

后端 未结 17 555
再見小時候
再見小時候 2020-12-03 05:19

Take the following code :

int *p = malloc(2 * sizeof *p);

p[0] = 10;  //Using the two spaces I
p[1] = 20;  //allocated with malloc before.

p[2] = 30;  //U         


        
17条回答
  •  眼角桃花
    2020-12-03 05:52

    Do :

    int *p = malloc(2 * sizeof(*p)); // wrong (if type is something greater than a machine word)
    
    [type] *p = malloc(2 * sizeof([type])); // right.
    

提交回复
热议问题