Hello;
When I wrote a function to print out an array,
void p_array(int arr[])
{
int i;
int size = sizeof(arr) / sizeof(int);
// int size = sizeof (arr) / sizeof (arr[0]);
for (i = 0; i < size; i++)
printf("%d ", arr);
printf("\n");
}
I could only print out the first two elements,( sometimes 8 out of 10 elements). What did I miss?
The problem seems to be the part
size = sizeof arr/sizeof(int);
size = sizeof arr /sizeof arr[0];
My understanding is (copied from stackoverflow):
sizeof returns the size in memory of the passed element. By dividing the size of an array by a single element size, you get the elements count. On the other hand, when counting elements in an array: sizeof(a) / sizeof(a[0]) will still work as well.
But my code does not! I saw this type online quite lot, but mine just does not work (Ubuntu 12.10, 64_bits kernel). Could anyone explain what is wrong with my code? Thanks a lot!