Borrito
Borrito

Reputation: 367

Casting a structure type included in the sizeof

I have a function which accepts the size mentioned as an argument like :

 sizeof(tcpstuct) * tcprules

Lets say

tcpstuct is a structure having type INT32 members . ( INT32 is of type int ,defined as INT32 due to platform dependency)

tcprules is a variable of type NAT32 .

If the function accepts another type say WORD32 . How should the cast go about ?

What I have tried :

(WORD32 ) (sizeof(tcpstuct) * (INT32 )tcprules )
(WORD32 ) ((INT32 )(sizeof(tcpstuct) * (INT32 )tcprules ))

But both of these throws in seg fault ! Do I need to cast the sizeof ?

EDIT : As all have pointed out , Seg fault was due to a bug elsewhere else thanks gdb

Upvotes: 0

Views: 433

Answers (2)

Kolli Ashok Kumar
Kolli Ashok Kumar

Reputation: 66

I do not see any potential crash in your statements. The segfault must be somewhere else.

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279245

If sizeof(tcpstuct) is the size of one "thingy", and tcprules is the number of "thingies", then there should be no need for any casts.

C automatically converts between different integer types, so whatever type your expression sizeof(tcpstuct) * tcprules has, should be converted to WORD32 (whatever that is, but assuming it's an integer type).

It's likely that the bug in your code is elsewhere, and very unlikely that this expression causes a segfault in any of the versions you've posted. Maybe the segfault is in the function you call.

Upvotes: 1

Related Questions