I need to store two distinct variables of 1 byte size in memory.

My memory system stores 4 bytes at one address; therefore, you cannot address byte 3 directly, and you have to logically access it after all 4 bytes are fetched of that address (correct me if I'm wrong please).

So, if I assign the following two variables: char var1 = "a" and char var2 = "b",

Will my system store them in memory at two different addresses?

Will 3 bytes in each of those addresses be useless (i.e., will the two variables occupy 8 bytes of memory)?

  • 1
    $\begingroup$ That's entirely up to the compiler. There's no answer more precise than "maybe, maybe not." $\endgroup$ – David Richerby Dec 9 '16 at 7:21
  • $\begingroup$ A compiler might still use logical unaligned 32-bit addresses where all the bits are meaningful. When a single byte is accessed, the address is aligned to 30 bits, 4 bytes are fetched, and then the wanted byte is extracted from those according to the last 2 bits of the original address. $\endgroup$ – chi Dec 9 '16 at 8:35

So your computer has 32 bits as the smallest addressable unit.

Your compiler has two choices: It can store var1 and var2 in two different sets of 8 bits in the same 32 bit unit, or it can store var1 and var2 in to different 32 bit units. The former produces likely more code, the latter uses more memory. It's up the compiler to decide.

If your programming language supports "pointer to char" as a type, then a pointer to var1 and a pointer to var2 will be different. Even if both are stored in the same 32 bit unit. A "pointer to char" will not be an address as it is used by the computer, but a combination of an address, plus some indication which of the four bytes of a 32 bit unit to access. Cray built machines that worked that way.

In the end, the compiler for your programming language is responsible to make everything work the way it is supposed to work according to the definition of the programming language, no matter how the underlying hardware works.

PS. The compiler also has the option to make char = 32 bit.


Not the answer you're looking for? Browse other questions tagged or ask your own question.