Regarding typedefs of 1-element arrays in C

前端 未结 2 473
自闭症患者
自闭症患者 2020-12-17 19:50

Sometimes, in C, you do this:

typedef struct foo {
   unsigned int some_data;
} foo; /* btw, foo_t is discouraged */
         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 20:44

    The only advantage to this method is nicer looking code and easier typing. It allows the user to create the struct on the stack without dynamic allocation like so:

    foo bar;
    

    However, the structure can still be passed to functions that require a pointer type, without requiring the user to convert to a pointer with &bar every time.

    foo_init(bar);
    

    Without the 1 element array, it would require either an alloc function as you mentioned, or constant & usage.

    foo_init(&bar);
    

    The only pitfall I can think of is the normal concerns associated with direct stack allocation. If this in a library used by other code, updates to the struct may break client code in the future, which would not happen when using an alloc free pair.

提交回复
热议问题