简体   繁体   中英

Is a pointer the same as a byte address?

Assume I have an array declared like this:

int *p = new int[size];

And p will of course point to the address of the first element. But since a byte is the smallest addressable unit of memory, does p actually point to the first byte of the first 4 bytes of the first element of the array?

The address of an int is not necessarily exactly the same as the address of the first byte ( char ) in its object representation. This is because some machines have native pointer registers that lack bits, such that sizeof (char *) != sizeof (int *) is possible.

Discounting that, though, the int * is convertible to the pointer to the first byte of the object representation via static_cast< char * >( p ) . You can pass the resulting pointer to std::memcpy to initialize another int or any POD class type whose first member is an int . ("First byte" therefore is defined as the one with the lowest address.)

For any machine you're likely to encounter in general-purpose computing, char * and int * are physically the same thing; their differences are just enforced by the compiler for the purpose of code safety. But there do exist exotic architectures where static_cast does something meaningful in this situation and something like reinterpret_cast would entirely fail perform the correct conversion.

Yes, it indeed points to the first of the four bytes. In the case of big Endian, the four bytes will look like 0 0 0 1. In the case of little Endian, the bytes will look like 1 0 0 0. So, just to be sure, in the case of big Endian, the first byte will contain a 0 while in the case of little Endian, the first byte will contain a 1.

In short, no. Because p is initialized as an int*, each element of p will take the number of bytes that an int does. To clarify:

int* p = new int[4];
for(int i = 0; i < 4; i++)
    p[i] = i;
cout << p[0] << " " << p[1] << " " << p[2] << " " << p[3];

This would output "0 1 2 3." You do not have to worry about individual bytes. In general, this is also true:

*p = p[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM