views:

130

answers:

5

I was programming normally when I realized that its probably not perfectly safe to assume an int is going to be a pointer to something 4 bytes in length.

Because Some of the aspects of C++’s fundamental types, such as the size of an int, are implementation- defined..

What if you're dealing with something (like a waveform, for example) that has 32-bit signed integer samples. You cast the byte pointer to (int*) and deal with it one sample at a time.

I'm just curious what's the "safe way" to acquire a 4-byte pointer, that ISN'T going to stop working if sometime in the future MSVC committee decides int is now 8 bytes.

Related

+7  A: 

There is a C99 header called stdint.h your compiler might have. It defines types like uint32_t, an unsigned 32-bit integer.

If not, check out Boost Integer, which mimics this header as <boost/cstdint.hpp>.


For storing pointers as integers, use intptr_t, defined in the same header.

GMan
Ah, http://stackoverflow.com/questions/269614/gcc-fixed-size-integers
bobobobo
I just found this: http://code.google.com/p/msinttypes/
bobobobo
A: 

One way I've seen it done is abstracting out the size with precompiler directives and typedefs. Then you use the abstracted types which will be correct for the set of systems you want to support.

John at CashCommons
+3  A: 

Use a pointer to uint32_t instead of int.

this type (and others) is defined in stdint.h and is part of the C99 standard

f4
A: 

Perhaps you could just use an assert on the sizeof(int) so that at least if your assumptions are violated in future you'll know.

John Burton
A: 

By far the easiest solution is to get a char* to a char[4]. On each and every platform, char[4] is a 4-byte object. For a entire waveform, you might need a char[4*512]

MSalters
The size of `char` is not defined; it has `CHAR_BIT` bits in it, and whilst `CHAR_BIT` is traditionally 8 there is no guarantee of this.
brone
I'm not sure who believed this comment and downvoted me. The standard is quite explicit that 'char` takes a byte (See 1.7, 5.3.3) The number of bits in a char (and by extension, in a byte) is left to the implementation, but the question was about a 4 byte object. `char[4]` is that object.
MSalters