sizeof
gives you the size of the array in chars (which are 1 byte long on most systems).
Each int is 4 chars long on your system, so to get the size in number of elements of the array, try:
sizeof(array) / sizeof(int)
Keep in mind that this will only work for arrays that are allocated statically. For arrays that are dynamically allocated (i.e. using malloc), you'll have to keep the length of the array safe elsewhere, or otherwise have some magic value at the end of the array that will let you iteratively find the size of the array (by looping through it until you get to the magic value). A common "magic value" is NULL.
Sizeof uses the typename
of the symbol provided to it (or the type provided to it) in order to determine size. An int varname[10]
takes sizeof(int) * 10 chars. If you were to use
int *varname = (int*)malloc(sizeof(int) * 10));
then, sizeof(varname)
would give you the same result as sizeof(int *)
, which is (in most cases) either 4 or 8, depending on whether you are on a 32 bit or 64 bit system.
Note that when using an initializer for an array:
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
Then sizeof(array)
will return the same value as it would were it run on:
int array[10];
This is because C would know the size of the array at compile time, and infer the type of array to be an array of 10 ints in both cases.