0

The following is my code

main(){

    char a[2]={'a','b'};
    copy_arr(a);
    int i=1;
    char *s=a;
    printf("s=%d\n and",sizeof(s)/sizeof(*s));
    printf("a=%d\n",sizeof(a)/sizeof(*a));
}

The output comes out to be s=4 and a=2 What does size of function returns in case of the pointer.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
Aditya Sharma
  • 389
  • 3
  • 11
  • It yields the size of the pointer object. – ouah Jan 17 '15 at 11:13
  • 1
    The size of just that: *a pointer*. (and `sizeof` isn't a function; its an operator). – WhozCraig Jan 17 '15 at 11:13
  • 1
    Using the `sizeof` operator on a pointer give you the size *of the pointer* and not what it points to. If you have a pointer to some memory, you have to keep track of the size yourself, there's no way in standard C to get the size of what a pointer pointer points to. Also, remember that arrays decays to pointers, so if you pass an array to a function (even if you declare the argument like an array) you will only have a pointer to the first element. – Some programmer dude Jan 17 '15 at 11:14
  • Can you please explain with an example – Aditya Sharma Jan 17 '15 at 11:15
  • 3
    again with `copy_arr`. What is that? – bolov Jan 17 '15 at 11:17
  • 1
    OT: It still is `int main(void)` at least. – alk Jan 17 '15 at 11:33

1 Answers1

1
sizeof(s)/sizeof(*s) 

This returns

sizeof(pointer)/ sizeof(s[0]) /* Note that s[0] = *s */

4/1 ( I guess pointer is of size 4 on your system) = 4

The other is

sizeof(a)/sizeof(*a)

sizeof(array)/sizeof(a[0]) which is (2*1)/1 = 2

Gopi
  • 19,784
  • 4
  • 24
  • 36