sizeof Explanation

Can someone please explain the behviour of this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#define SIZE 10

void size(int arr[SIZE])
{
    int b[10];
    printf("size of array is:%d\n",sizeof(arr));
    printf("size of array is:%d\n",sizeof(b));
}

int main()
{
    int arr[SIZE];
    size(arr);
    return 0;
}
sizeof returns the size of a variable (bytes, e.g. sizeof(int) on most PCs will be 4; sizeof(char) will be 1 on most PCs, etc). In this case it is returning the amount of elements in the arrays, so ten.
In this case it is returning the amount of elements in the arrays, so ten.
You sure about that?
The sizeof operator always returns the number of bytes used by its argument, using the most complete information available.

The int arr[WHATEVER] is the same as an int*, which has the size of a pointer to int.

However, the 'b' on line 6 is a known array type, so its size is the same as the size of ten ints.

Keep in mind that the argument to your 'size' function on line 4 is not necessarily the 'arr' aray declared on line 13. It makes no difference that they are declared with the same name and subscripts -- they are, quite simply, not necessarily the same objects. Hence, no further information about the original object is available inside the function (lines 5 through 9).

When used as a pointer, an array will degrade its type to a pointer to the first element. The reverse is not possible.

Hope this helps.
You sure about that?

I was fairly sure it would return the amount of elements in an array. It usually does, anyway... Theoretically it should return the same value as (strlen(arr)) * int* but it never seems to.
Last edited on
(strlen(arr)) * int*
Huh??

it never seems to
Have you considered that maybe that's because your theory is wrong?
Have you considered that maybe that's because your theory is wrong?

No. I'm never wrong.

On a serious note; yes. But it always seems to return the amount of elements in an array.

http://en.wikipedia.org/wiki/Sizeof#Using_sizeof_with_arrays
When sizeof is applied to an array, the result is the size in bytes of the array in memory.


(strlen(arr)) * int*

Sorry, I meant (strlen(arr)) * sizeof(int*).
When sizeof is applied to an array

^That is the key thing. In the function, you pass a pointer to the array, not the array itself.
Sorry, I meant (strlen(arr)) * sizeof(int*).
I must have unconsciously compensated for your error, because I understood it like that. It still doesn't make sense.
Topic archived. No new replies allowed.