Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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

like image 796
Nick Bolton Avatar asked Feb 25 '10 17:02

Nick Bolton


People also ask

Is a char * the same as char in C?

Difference between char s[] and char *s in C There are some differences. The s[] is an array, but *s is a pointer. For an example, if two declarations are like char s[20], and char *s respectively, then by using sizeof() we will get 20, and 4. The first one will be 20 as it is showing that there are 20 bytes of data.

What does char * [] mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

What is size of char pointer in C?

The size of the character pointer is 8 bytes. Note: This code is executed on a 64-bit processor.


2 Answers

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

like image 177
AndiDog Avatar answered Oct 04 '22 20:10

AndiDog


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

like image 41
Reed Copsey Avatar answered Oct 04 '22 19:10

Reed Copsey