Hi, how do I know how many bytes I've initialised to a datatype?
ie:
int x; <--Could this mean I've reserved 1 byte?
How do I initialize a fix length of bytes?
Printable View
Hi, how do I know how many bytes I've initialised to a datatype?
ie:
int x; <--Could this mean I've reserved 1 byte?
How do I initialize a fix length of bytes?
Use sizeof() perhaps?
See Salem's answer.Quote:
Hi, how do I know how many bytes I've initialised to a datatype?
ie:
int x; <--Could this mean I've reserved 1 byte?
BTW, instead of "how many bytes [have I] initialised to a datatype", you might more properly put it as "how many bytes were reserved [on the stack] when I declared this variable".Code:int x;
printf("%d\n", sizeof(x));
I have no idea why you would want to do this, but an ordinary local array of characters should require CHAR_BIT/8*elements bytes. CHAR_BIT is usually 8, soQuote:
How do I initialize a fix length of bytes?
should usually allocate 16 bytes. (This won't work in structures if that's what you're thinking.)Code:char dummy[16];
In C/C++, a byte is defined as whatever the size of a (signed or unsigned) char is, so your definition always allocates 16 bytes. The catch, of course, is that a byte (in C/C++) isn't always 8 bits, but for many purposes, such as calling malloc(), it doesn't matter.
>sizeof char is 1, not 1 byte, just 1...
sizeof returns the size in bytes.
No it doesn't. It returns the size in chars. [edit] <-- this is wrong [/edit]
[edit]
Hang on...
Give me a second, I'll try to find my point of confusion. I think there's a reference book I have around here some place that says it's "size in chars", which was fresh in my mind, which is why I thought to double check it once more.Quote:
6.5.3.4 The sizeof operator
Constraints
1 The sizeof operator shall not be applied to an expression that has function type or an
incomplete type, to the parenthesized name of such a type, or to an expression that
designates a bit-field member.
Semantics
2 The sizeof operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. The result is an integer. If the type of the operand is a variable length array
type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an
integer constant.
[/edit]
[edit2]
I may be confusing another thread. I'm getting too old I guess.
[/edit2]
Quzah.
The MSVC 2005 documentation says that (in C) sizeof returns the number of bytes and (in C++) sizeof returns the size with respect to char.
Maybe it's something like that I was thinking of. I'll blame old age and no cup of morning coffee before posting. Here is another FAQ type read, but it relates to C++.
If I had been awake enough, I wouldn't have edited that, taken advantage of the upcoming date, and tried to pass it off as an elaborate ruse.
Quzah.