0

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
Sizeof an array in the C programming language?

#include<stdio.h>

void doit(char x[10]){
    printf("%d\n", sizeof(x));
}

void main(void){
    char x[10];
    printf("%d\n", sizeof(x));
    doit(x);
}

** I don't know why my question is removed first time. ** Two outputs here are different. Apparently the first one knows x is an array and second one only knows it a ptr. My question is why compiler knows that in the first case it's an array instead of a ptr?

Community
  • 1
  • 1
uvdn7
  • 83
  • 4

1 Answers1

0

I am no compiler expert but during the compilation phase, the compiler performs something called semantic analysis. During this phase, type checking is done. sizeof is also a compile time operator ( barring VLArrays probably ) and during type checking the compiler determines that in main, x is an array and in doit function it is a pointer.

Its like, the compiler is the owner of the house and hence it knows the type of its tenants.

Read about the compilation process on wiki

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
  • The `doit` function parameter _is a pointer_. When an array is passed as a function parameter it always decays to a pointer. – Blastfurnace May 07 '12 at 17:37
  • @Blastfurnace I guess I haven't contradicted to the point you are making? May be the wording confuses you? Yes the function parameter is indeed a pointer as you cant pack arrays and send them – Pavan Manjunath May 07 '12 at 17:39
  • You kind of dance around the answer, but never really hit it. The issue is that when an expression of array type appears in most contexts (such as in a function call), it is converted ("decays") to an expression of pointer type. IOW, you have the cause and effect reversed. The conversion doesn't happen because `doit` expects a pointer; rather, `doit` expects a pointer because the conversion happens. – John Bode May 07 '12 at 18:37