2

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?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • 2
    The variable you get on defining array is a pointer. You cannot get the size of an array from a pointer. See this http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array – user568109 May 21 '13 at 03:34
  • dupe and flagged as such – xaxxon May 21 '13 at 03:35

2 Answers2

4

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]) );
paddy
  • 60,864
  • 6
  • 61
  • 103
0

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740