malloc(sizeof(int)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(int))

后端 未结 2 1810
别那么骄傲
别那么骄傲 2020-12-02 12:46

I acknowledge that all three of these have a different meaning. But, I don\'t understand on what particular instances would each of these apply. Can anyone share an example

2条回答
  •  广开言路
    2020-12-02 13:06

    The syntax pattern that is most foolproof is:

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

    This syntax will not force you to change the code if the type (and or size...) of *p changes, eg in

     struct mysstruct *q;
     q = malloc (cnt * sizeof *q);
    

    Which will avoid problems like

    struct mysstruct *z;
    z = malloc (cnt * sizeof(struct hisstruct)); // Auch!
    

    , plus: the sizeof expr form is also shorter.


    UPDATE: to demonstrate the correctness of p = malloc(CNT * sizeof *p) this test program:

    #include 
    #include 
    
    struct mystruct {
            int i;
            char s[14];
            };
    int main(void)
    {
    struct mystruct *p;
    size_t siz;
    
    siz = sizeof p;
    printf("Sizeof p := %zu\n", siz);
    
    siz = sizeof *p;
    printf("Sizeof *p := %zu\n", siz);
    
    printf("Allocating %zu (%u structs, each of size %zu) bytes to be assigned to p...\n"
            , 10u * sizeof *p
            , 10u, sizeof *p
            );
    p = malloc(10 * sizeof *p);
    
    return 0;
    }
    

    Which outputs here:

    Sizeof p := 8
    Sizeof *p := 20
    Allocating 200 (10 structs, each of size 20) bytes to be assigned to p...
    

提交回复
热议问题