Nick Bolton
Nick Bolton

Reputation: 39610

Using C, why would a char * type be of size 2 in one place, but 4 in another?

From a question on the Practice C test from GeekInterview, why is the size of ptr1 2, while ptr2 and ptr3 are size of 4?

main() 
{ 
char near * near *ptr1; 
char near * far *ptr2; 
char near * huge *ptr3; 
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3)); 
} 

Output: 2 4 4

Upvotes: 9

Views: 2510

Answers (2)

AndiDog
AndiDog

Reputation: 70208

When working on architectures with segmented memory (like x86 real mode), one can distinguish three types of pointer addresses (examples for x86 in segment:offset notation):

  • near

    Only stores the offset part (which is 16-bit) - when resolving such a pointer, the current data segment offset will be used as segment address.

  • far

    Stores segment and offset address (16 bit each), thus defining an absolute physical address in memory.

  • huge

    Same as far pointer, but can be normalized, i.e. 0000:FFFF + 1 will be wrapped around appropriately to the next segment address.

On modern OSes this doesn't matter any more as the memory model is usually flat, using virtual memory instead of addressing physical memory directly (at least in ring 3 applications).

Upvotes: 9

Reed Copsey
Reed Copsey

Reputation: 564691

Because you're using near pointers vs. far pointers. A far pointer requires two 16 bit addresses, in this case.

(The "huge" specifier is a non-standard far pointer syntax, for handling some specific far pointer cases...)

Upvotes: 5

Related Questions