Code_Warrior
Code_Warrior

Reputation: 1

data type storage in C

I want to understand how declaring a variable as char saves memory than declaring int or short. I know the fact that declaring char reserves 1 byte in memory while 2 or 4 bytes get reserved for int. So now, suppose in a 16 bit processor, a variable char is stored at say location 0xABCD. Since it is a 16 bit processor, 1 byte or 8 bits of the 16 bits at the address 0xABCD is reserved for char. Now an int variable is stored at location 0xBCDE, accordingly it will reserve 16 bits of the 16 bits available at the location 0xBCDE. So now what I really want to know is what happens to the 8 bits that are at the location 0XABCD left over after reserving memory for char variable considering the fact that at one memory location only one variable can be stored.

Upvotes: 0

Views: 313

Answers (2)

Jongware
Jongware

Reputation: 22478

Memory addresses do not work like "variables". They can not store 8 or 16 bits, they can only and exclusively store exactly 8 bits (one single byte). (a)

When an int gets stored "at" an address, it takes up more space -- not "in" that same address, but flowing over in next memory addresses, immediately following "the" memory address. Thus, if you store a char at 0xABCD, the compiler knows it's safe to assume a next value can be stored at 0xABCE. If you store a 16-bit short at 0xABCD, the compiler knows the data gets stored in 0xABCD and 0xABCE.(b)


(a) For sake of clarity. There are configurations where a single memory unit can hold more or less bits (historically, the 8th bit was meant for error checking, and so one could only store 7 significant bits of data in each location).

(b) Again, for sake of clarity. A compiler may decide to use 4, or even 8 bytes of memory space for each type of char, short, and int. This is because reading and writing a "native" size value from memory may be faster than "odd" sizes. The "native" size of data is the one a CPU is designed specifically for.

Upvotes: 1

Cruel_Crow
Cruel_Crow

Reputation: 349

If char is being stored at adderss 0xABCD, only the single memory cell, which size is usually 8 bits or 1 byte, which is located by address 0xABCD is being used for this variable (let's assume we don't use data structure alignment). So, memory cell 0xABCE (or 0xABCC - it depends on memory architecture) is not being used at all.

Now, for int. Actually, ANSI C doesn't say how much memory (cells/bytes) should int use. Usually, on 32 bit OSes - it's 32 bits or 4 bytes, on 64 bit OSes - 64 bits or 8 bytes.

It is safe to assume, that on our 16 bit processor int variable will be stored in 16 bits or 2 bytes (2 memory cells): 0xABCD and 0xABCE (or 0xABCC).

Upvotes: 0

Related Questions