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
There is a C99 header called stdint.h
your compiler might have. It defines types like uint32_t
, an unsigned 32-bit integer.
Since C++11, your compiler is required to have this header. You should include it with #include <cstdint>
.
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.
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
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.
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.
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]
精彩评论