ManicQin wrote:
> Hi all.
> I'm trying to get the size of a variable in a struct by his relative
> postion i.e.
That's the wrong way.
It's even more wrong if you need to define offsetof:
> #define offsetof(s,m) (size_t)&(((s *)0)->m)
offsetof is part of the language. It should be defined in <stddef.h>,
if you don't otherwise have it.
> struct ThePimp{
> char rings[10];
> char blings[20];
> };
> int sizeOfBling = sizeof( (*char)&ThePimp +
> (char)offsetof(ThePimp,blings) );
If you have an instance of the struct, you can get the sizea
immediately. Obviously your code is meaningless, since ThePimp is a
struct tag and trying to take the address of a struct tag is just silly.
> (If I have any syntax mistakes please ignore)
How can we?
> You can easily predict that sizeOfBling will be 4... (sizeof(int*))
No, I cannot. rings and blings are arrays of chars, not pointers to
int. Their sizes are _not_ sizeof (int *). (And sizeof(int *) is by no
means assured to be 4).
> Is there any way to acomplish it?
Consider the following program. Is there anything you need (other than
a completely spurious claim that a char array is a pointer-to-int) that
it does not give?
#include <stdio.h>
#include <stddef.h>
struct ThePimp
{
char rings[10];
char blings[20];
};
int main(void)
{
struct ThePimp pimpinstance;
printf("For this implementation,\n"
"The size of a struct ThePimp is %zu\n"
"and the size of an instance of it is %zu.\n"
"The size of the rings array member is %zu,\n"
" and it has %zu elements.\n"
"The size of the blings array member is %zu,\n"
" and it has %zu elements.\n\n"
"The offset of the rings array member is %zu;\n"
"The offset of the blings array member is %zu.\n",
sizeof(struct ThePimp),
sizeof pimpinstance,
sizeof pimpinstance.rings,
sizeof pimpinstance.rings / sizeof *pimpinstance.rings,
sizeof pimpinstance.blings,
sizeof pimpinstance.blings / sizeof *pimpinstance.blings,
offsetof(struct ThePimp, rings),
offsetof(struct ThePimp, blings));
return 0;
}
For this implementation,
The size of a struct ThePimp is 30
and the size of an instance of it is 30.
The size of the rings array member is 10,
and it has 10 elements.
The size of the blings array member is 20,
and it has 20 elements.
The offset of the rings array member is 0;
The offset of the blings array member is 10.
--
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
-- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line. Sorry.


|