struct a
{
int a;
char s;
float b;
};
int main()
{
printf("%d" , sizeof(struct a));
}
output = 12
HOW?
Explain me
How to implement function which is equal to sizeof operator in c?
You can't. A C function only accepts values, not types, so there's no way to make it generic. If you know the type of the object you're trying to calculate the size of then you can create one on the stack and calculate the difference between the start address and the end address, something like this:
int SizeOfStructA()
{
struct a tempvar;
struct a * start = %26amp;tempvar;
struct a * end = start + 1;
return (int)end - (int)start;
}
If you already have a variable on the stack then you can use a define to get its size:
#define SizeOf(X) ((int)(%26amp;X+1) - (int)%26amp;X)
struct a test;
int size = SizeOf(test);
These assume that it's safe to cast an address to an int on your system...in modern operating systems this isn't advised.
Reply:Hi,
size of operator will give 7. Because
int type takes 2 bytes
char type takes 1 byte
float type takes 4 bytes
Total 2+1+4=7 bytes.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment