sizeof(array) / sizeof(int) [duplicate]

坚强是说给别人听的谎言 提交于 2020-01-15 07:29:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!