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.
"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.
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?).