c - Is it possible to get the size of the item the pointer is pointing at? -


is possible find size of item_t through pointer?

typedef struct item {   char x;   char y;   char life; }item_t;  void main (void) {   item_t test;   void *ptr = &test;   printf("%d\n",sizeof(ptr)); } return: 8 

not if ptr of type void* -- shouldn't be.

you can't dereference void* pointer. can convert other pointer type , dereference result of conversion. can useful, more should define pointer correct type in first place.

if want pointer item_t object, use item_t* pointer:

item_t test; item_t *ptr = &test; printf("%zu\n", sizeof(*ptr)); 

this give size of single item_t object, because that's type ptr points to. if ptr uninitialized, or null pointer, you'll same result, because operand of sizeof not evaluated (with 1 exception doesn't apply here). if ptr initialized point initial element of array of item_t objects:

ptr = malloc(42 * sizeof *ptr); 

sizeof *ptr still give size of 1 of them.

the sizeof operator (usually) evaluated @ compile time. uses information that's available compiler. no run-time calculation performed. (the exception operand type variable-length array.)

the correct format printing value of type size_t (such result of sizeof) %zu, not %d.

and void main(void) should int main(void) (unless have reason use non-standard definition -- don't). if book told define main return type of void, better book; author doesn't know c well.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -