问题
Within a function I have declared an array:
int char_count_array[118] = {0};
Later on, I pass this array to a function and calculate the following:
int xx = sizeof(char_count_array);
int xy = sizeof(char_count_array)/sizeof(int);
However, the result I get is: xx = 4 xy = 1
I thought I would be getting: xx = 472(118 * 4) xy = 118 (472 / 4).
Would anyone know what I am doing wrong here?
回答1:
If you are passing it to a function, it's most likely going in as int*
instead of int[118]
. So your sizeof
is returning the size of a pointer. When you pass C arrays to functions, it's conventional to also pass the number of elements.
my_func( arr, sizeof(arr)/sizeof(arr[0]) );
回答2:
Most likely when you are passing the array to function you are actually passing a pointer
which has a size of 4
on your machine. If you need to know the size of the array you need to pass the size as another parameter to the function.
来源:https://stackoverflow.com/questions/16661605/sizeofarray-sizeofint