What is the Best Practice for malloc?

后端 未结 3 2047
南旧
南旧 2020-12-18 04:43

Which if any of the following are correct and would be considered best practice to create a char string capable of holding 100 characters?

char * charStringA         


        
3条回答
  •  自闭症患者
    2020-12-18 05:22

    The most general form is:

    #include 
    
    typedef struct { int a; char b[55]; } Thing;
    
    Thing *p;
    p = malloc (100 * sizeof *p);
    

    This works indepentely of the actual definition of Thing, so if you would "reuse" the line as

    Typedef { float water; int fire; } OtherThing;
    OtherThing *p;
    p = malloc (100 * sizeof *p);
    

    it would still function as intended.

    The original case would yield:

    char *p;
    p = malloc (100 * sizeof *p);
    

    , where the sizeof *p would of course be superfluous (since sizeof(char) == 1 by definition) , but it won't hurt.

    BTW: this answer is mostly about style. Syntactically, all variants are acceptible, given you include stdlib.h (or manually introduce a prototype for malloc())

提交回复
热议问题