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

后端 未结 17 553
再見小時候
再見小時候 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:36

    Because malloc() allocates in BYTES. So, if you want to allocate (for example) 2 integers you must specify the size in bytes of 2 integers. The size of an integer can be found by using sizeof(int) and so the size in bytes of 2 integers is 2 * sizeof(int). Put this all together and you get:

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

    Note: given that the above only allocates space for TWO integers you are being very naughty in assigning a 3rd. You're lucky it doesn't crash. :)

提交回复
热议问题