I am confused about a function dictCreate()
in file dict.c of redis
implementation. I am going to paste the code here:
/* Create a new hash table
* T = O(1)
*/
dict *dictCreate(dictType *type, void *privDataPtr) {
dict *d = zmalloc(sizeof(*d));
_dictInit(d, type, privDataPtr);
return d;
}
variable d
is used in zmalloc(sizeof(*d))
, but theoretically it will exist when this line was executed. So my question is how it is possible to use variable d
before it is declared?
sizeof
is not a function, it is an operator. It is executed (evaluated, to be exact) at compile time, so the scope or lifetime you're thinking about d
, does not apply here. All it needs to know is the type of *d
and that is known at compile time. Sufficient.
The statement
dict *d = zmalloc(sizeof(*d));
is equivalent to
dict *d;
d = zmalloc(sizeof(*d));
So, dict *d
declares d
as a pointer to dict
type and = zmalloc(sizeof(*d));
used for initialization. dict *d = zmalloc(sizeof(*d));
declares d
as dict *
and then initializes it in single line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With