three C tips
-
This example says
sizeof
can be used on a dereferenced pointer, even if it is of typestruct *
, and doesn’t point to anything. This is because the size of the struct is known at compile time.#include <stdio.h> struct abc { int a; double b; char *c; }; int main() { struct abc *p; printf("%d\n",sizeof(*p)); return 0; }
Output:
16
Note that there is an alignment issue. If we change the definition of struct abc to:
struct abc { char a; double b; char *c; };
The result will still be 16 since it’s 4-byte-aligned.
Note. This program is tested on a 32-bit machine.
-
This is a valid struct initialization. In this way you don’t care about the order of items.
struct abc { int a; double b; char *c; }; struct abc item = { .b = 3.14, .c = "ccccc", .a = 10, };
Also note that the compiler doesn’t care about the last comma. It’ll be OK whether you add it or not. I don’t know whether it’s a compiler-specific issue. But it looks fine.
-
Variables length array is a new feature in C99. In this case this is an execution-time
sizeof
.#include <stdio.h> int calc(int k) { char buf[k+12][k+3]; return sizeof(buf); } int main() { printf("%d\n",calc(10)); return 0; }
Output:
286