Should I use "typedef struct" or not? Which are the pros and cons ?
It's just subjective coding style. The most common style is to use a typedef. One advantage is that it makes the code behave just like C++. Typing out struct name
explicitly is ok too, a style favoured by Linux. Neither style is obviously right or wrong.
However, for self-referencing structs then regardless of style you must always write the pointer member with struct
notation.
typedef struct foo
{
struct foo* next;
} foo_t;
foo_t* next
won't work because the typedef is not complete at that point. foo
however is a "struct tag", not a type name, so it follows different rules. If you wish to use the typedef name internally, then you have to forward-declare the struct:
typedef struct foo foo_t; // forward declaration
struct foo
{
foo_t* next;
};
When I allocate memory some told me that calloc is better than malloc because it does the same job but better...
When someone tells you that, ask them how exactly is calloc
any better. When programming, critical thinking is very important.
malloc
allocates a chunk of memory but does not initialize it to known values. Since there is no initialization, malloc
is faster than calloc
.
calloc
allocates a chunk of memory, or optionally an array of chunks placed in adjacent memory cells. It zero-initializes all memory, meaning that it has known default values. Because of this, it is slower than malloc
.
So which is "better", faster or pre-initialized? Depends on what you want to do.