I was doing a programming exercise for C and I came through this question
what on your system has restriction on pointer types char* , int* and void*? For example, may an int* have an odd value? Hint:alignment
I have nothing to show what I have done, I have trouble understanding the question
CodePudding user response:
Objects of a given type can only be stored in memory at addresses that are a multiple of their alignment.
Also, a valid pointer contains the memory address of an object of its type.
By combining these two, we can say that a valid pointer must absolutely contain an address that is a multiple of the alignment of its matching type.
You can ask the compiler to give you the alignment of a type for its current target system by using the alignof()
operator. For example:
#include <iostream>
int main() {
std::cout << "pointers to float must contain a multiple of " << alignof(float) << "\n";
}
CodePudding user response:
This is not an answer. It’s just an example showing that the question is way too open-ended. Is it referring to the alignment of data structures outlined by a language standard or perhaps to memory alignment requirements of a particular hardware platform?
Let me share a secret:
#include <cstdint>
#include <ios>
#include <iostream>
using std::uint8_t;
using std::uint32_t;
using std::uint64_t;
int main() {
const uint64_t something{0x1020304050607080};
std::cout << std::hex;
for (const uint32_t shift : {0, 1, 2, 3, 4}) {
const uint32_t *const pointer =
reinterpret_cast<const uint32_t*>(
reinterpret_cast<const uint8_t*>(&something)
shift);
std::cout << pointer << " --> " << *pointer << std::endl;
}
}
Don’t try this^^^ at home.