sizeof type pointed to by pointer?

  • Thread starter Thread starter Ole
  • Start date Start date
O

Ole

Hi,

Doing this will work:

double *dPointer;
result = sizeof(*dPointer);

if I want the size (in this case 8) of the type that the pointer is pointing
at, but is there a more correct way to obtain it?

Thanks
Ole
 
Ole said:
Doing this will work:

double *dPointer;
result = sizeof(*dPointer);

if I want the size (in this case 8) of the type that the pointer is
pointing at, but is there a more correct way to obtain it?

I don't know what "more correct" means in this context.

That said, both

sizeof(double)

and

sizeof(*dpointer)

will yield the same result while

sizeof(dpointer)

yields the size of the pointer itself.

Does that help?

Regards,
Will
 
Ole said:
Hi,

Doing this will work:

double *dPointer;
result = sizeof(*dPointer);

if I want the size (in this case 8) of the type that the pointer is pointing
at, but is there a more correct way to obtain it?

Nope, what you've got is fine. sizeof is guaranteed not to evaluate the
expression passed to it, so although your code appears to dereference an
uninitialized pointer, in fact it doesn't.

Tom
 
Tom Widmer said:
Nope, what you've got is fine. sizeof is guaranteed not to evaluate the
expression passed to it, so although your code appears to dereference an
uninitialized pointer, in fact it doesn't.

Tom

Thanks, I was worried about if sizeof would evaluate to a different result
in some special cases like uninitialized pointers etc.

Ole
 
Ole said:
Thanks, I was worried about if sizeof would evaluate to a different result
in some special cases like uninitialized pointers etc.

No, sizeof is a purely compile-time operator, with no support for
polymorphism or RTTI. This allows you to use it in place of a literal
constant, for example to declare the size of an array:

union {
double dbl;
char bytes[sizeof(double)];
};
 
Back
Top