First of all, thank you for your answer.
Irrwahn Grausewitz wrote:
> Martin Pohlack <> wrote:
>
>
>> Hi,
>>
>> I have a funtion which shall compute the amount for a later malloc.
>> In this function I need the sizes of some struct members without
>> having an instance or pointer of the struct.
>>
>> As "sizeof(int)" is legal I assumed "sizeof(struct x.y)" to be
>> legal too. But is is not:
>>
>> #include <dirent.h>
>>
>> int dir_dirent_size(dir_t * dirp) { int len;
>>
>> // syntax error len = sizeof(struct dirent.d_ino) + sizeof(struct
>> dirent.d_off) + sizeof(struct dirent.d_reclen) + strlen(dirp->name)
>> + 1;
>>
>> return len; }
>>
>>
>> I can fix this problem using a dummy pointer to a dirent struct:
>>
>> #include <dirent.h>
>
> This is a non-standard header. Anyway, I suppose it declares (at
> least) the struct dirent you are referring to later...
yes, the struct is declared there, but that should not be important for
my example. Anyway, the struct looks like follows:
struct dirent
{
long d_ino;
off_t d_off;
unsigned short d_reclen;
char d_name[256];
};
>> int dir_dirent_size(dir_t * dirp) { int len; struct dirent * temp;
>>
>> // syntax error len = sizeof(temp.d_ino) + sizeof(temp.d_off) +
>> sizeof(temp.d_reclen) + strlen(dirp->name) + 1;
>>
>> return len; }
>>
>>
>> However, I'm curious what would be the 'right thing' (tm) to do.
>
>
> You should change the above to:
>
> len = sizeof temp->d_ino + sizeof temp->d_off + sizeof temp->d_reclen
> + ...
>
> as temp is a *pointer* to a struct and the parantheses are optional,
> when applying the sizeof operator to an object, not a type.
yes, you are right. I must confess I constructed the example without of
trying to recompile it after the last changes. So, what you wrote is
what I head in mind

. However, optional is not the same as forbidden.
So I consider the question of parantheses as a question of style.
> Further more, if your intention is to calculate the size of the
> /whole/ struct, inclusive possible padding, you should just write:
>
> len = sizeof *temp + ...
Yes, of course that is what I *would* do. But I don't want that.
I want to compute the size of *parts* of the struct *without* of having
an instance of it, as it is possible to compute the size of an int by
writing:
x = sizeof(int);
On the contrary it is possible to do it with an instance:
int a;
x = sizeof(x);
or
int *a;
x = sizeof(*a);
For more complex types it only seems to be possible to use one of the
last cases.
Or is there a way???
btw. a (local) friend of mine suggested the following:
len = sizeof (((struct dirent *) 0)->d_ino);
greets,
Martin