Welcome, Guest. Please login or register.

Author Topic: sizeof (*VarPtr) possible ?  (Read 5329 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Cymric

  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 1031
    • Show all replies
Re: sizeof (*VarPtr) possible ?
« on: January 30, 2007, 11:12:31 PM »
Quote
How big is this?

struct AudioObject {
  unsigned long numSampleFrames;
  unsigned short sampleRate;

  ...

  signed short waveData[1]; /* memory beyond this point is wave data */
};

This is of course not (old) standard ANSI-C, and therefore it is no surprise that sizeof() fails to generate the proper value. This hack did work unofficially on nearly every compiler out there, which is why it was merged into the C9X standard. And in that standard, the sizeof() result has been changed to return the size of the struct without the incomplete array. It also specifies what happens in the case of padding (it's added).

Granted, it may not be IOTTMCO (Intuitively Obvious To The Most Casual Observer), and I will concede to my foot now having more holes than actual foot for misunderstanding sizeof()---but that's what you get from not understanding the keyword itself, isn't it...?

(Later edit: Your example uses a complete array, namely with 1 element. Therefore sizeof() will return the size of the struct as defined. If you leave out the 1, then sizeof() returns the size of the struct at the moment the array would appear in memory.)

Quote
I've seen such "open ended" structures in a lot of places. Of course sizeof() cannot know you might have malloc()'ed this structure with an additional 200K worth of sample space.

See above.

Quote
So, you can only rely on sizeof() when you fully understand its necessary limitations.

See above, too.

Quote
To you, yes. Never underestimate the ability of people to overlook the obvious however. I have seen code where I work that would give you hives.

That's what makes these languages such a nightmare and so strangely addictive at the same time: by the time you feet are just shreds, and your head is now a mass of sores from pulling out the hairs and their follicles, and you do find the answer, you will NEVER forget the lesson you learned.

And then appreciate languages which hide such details all the more.
Some people say that cats are sneaky, evil and cruel. True, and they have many other fine qualities as well.