Wallacy
Wallacy

Reputation: 35

How to know struct size casted to void pointer in C?

In my code, there are 2 types that refer a struct:
TypeX and typeX.

TypeX is a void pointer, and typeX is the struct type.
After allocating memory to a typeX variable, I passed it (casted) to a TypeX variable (or a void pointer).

I want to get the size of following struct casted to void pointer:

Code

#include <stdio.h>
#include <stdlib.h>

struct _typeX {  
    double a;  
    double b;  
};  

typedef struct _typeX typeX;
typedef void* TypeX;

int main(int argc, char const *argv[]) {  
    TypeX t = NULL;  
    typeX *t0 = NULL;

    t0 = (typeX *) calloc(1, sizeof(typeX));

    t0->a = 123;
    t0->b = 456;

    t = (TypeX) t0;

    printf("%lu\n", sizeof(*t0));
    printf("%lu\n", sizeof(*t));

    free(t);

    return 0;  
}  

But struct size and void pointer size are different:

Output

16
1

Is there any way to identify the struct size correctly by passing a void pointer as parameter?

Upvotes: 1

Views: 1441

Answers (1)

melpomene
melpomene

Reputation: 85897

First off, having both typeX and TypeX but with very different meanings is very confusing. Also, don't hide pointers behind typedefs.

As for your question: No, you cannot recover the size of the object that t is pointing to.

sizeof EXPR gives you the size of the type of EXPR (in bytes). It does not matter what the actual value is (in fact, EXPR isn't even evaluated1).

Consider

char c;
int i;
double d[100];

TypeX p1 = (TypeX)&c, p2 = (TypeX)&i, p3 = (TypeX)d;

All of p1, p2, p3 have the same type, so sizeof will return the same value for all of them, even though the objects they're pointing to have very different sizes.

Finally, sizeof (void) is not a thing in standard C. GCC allows it as an extension (and returns 1), but it will warn you that this is non-standard if you enable -pedantic diagnostics.

1 - With one relatively obscure exception, which I'm just going to ignore.

Upvotes: 1

Related Questions