|
|
|
|
|
by somenits
1086 days ago
|
|
Good article, a couple nits/additional notes: 1. The article points out you should compare structs field by field, but it doesn't explain why memcmp wouldn't work. The reason is that the padding between the fields might not necessarily be zeroed in all cases. Field by field comparison is resilient to this. 2. The article proposes this for dynamic allocation: struct Vector2D *vec = malloc(sizeof(struct Vector2D));
I think it's better to use the variable name inside sizeof, so like this: struct Vector2D *vec = malloc(sizeof(*vec));
This helps you in the case where you change the type of the variable to different kind of struct. If you change the variable name, you're probably doing a find/replace anyway, and it will almost certainly fail to compile even if you miss it. |
|
In the end, the only justification for the latter rather than the former is that the pointer name is often a short name like vec, and so sizeof *vec is shorter than the alternative.
That has advantages.
If there is a typo in a short name, you're more likely to see it.
I can easily miss the typo:
The sizeof <object-expr> also doesn't require parentheses, so it's shorter by two characters right off the bat.