1

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

Community
  • 1
  • 1
bobobobo
  • 64,917
  • 62
  • 258
  • 363

5 Answers5

7

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.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • Since the question is tagged as C++, it should be noted that is `cstdint` should be used instead of `stdint.h`. This declares the types in namespace `std`, e.g. `std::uint32_t`. – Jens Feb 09 '16 at 07:53
  • @Jens: Yup, strange since I typically treat plain C includes in C++ as a smell. Fixed. – GManNickG Feb 10 '16 at 01:52
3

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.
  • 3,814
  • 1
  • 23
  • 30
0

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
  • 15,990
  • 10
  • 70
  • 110
0

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.

jcoder
  • 29,554
  • 19
  • 87
  • 130
0

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
  • 173,980
  • 10
  • 155
  • 350
  • 1
    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. –  May 21 '10 at 23:24
  • 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 May 25 '10 at 15:58