Hi, this is not a homework or assignment. I am preparing for interviews. I just wanted to know how do I find out say the next 6 byte aligned address given any random address? Hope I am clear. Any code or explanation will be appreciated. Thanks.

Recommended Answers

All 4 Replies

"aligned" is the key word -- what alignment? Not all compilers use the same alignment factor, and some compilers have options to change the alignment. Microsoft compilers have a #pack paragma what lets you align different parts of the program with different alignment factors.

what excatly you want Byte Alignment or do you want to check whether address are in consecutive positions ?

6-byte alignment is rare, I assume you want a generic reply. It could depend on integer divide, which always truncates (never rounds). Avoid negative numbers by using unsigned. The first problem is the length of a pointer, which can be up to 64 bits long. Here is a generalized example

unsigned long long alignment = 6;
unsigned long long addr = (unsigned long long) pointer; // not assumed to be aligned.
addr = pointer / alignment; // Aligned (also divided by 6)
addr++;                     // Next aligned pointer (still divided by 6)
addr *= alignment;          // Next aligned pointer
pointer = (thepointertype *) addr;

It should work for any arbitrary alignment (such as 1, 5, 7, 64, or 12345).
Getting the compiler to generate structures with 6-byte alignment is harder, and the pointer may not actually be useful (perhaps to point to a string?).

Hey thanks a lot. That was just what I wanted. I know I am replying late but better late than never.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.