0

I'm learning the C Language.

I need the size of the int array(passed in the parameter of a function).

I'm able to get the size of int array that using:

int size = sizeof(arr) / sizeof(int);    

But, When I'm using the same code on parameterized array, the above piece of code is not working for me.

Program:

void printArraySize(){
    int arr[]= {1, 2, 3, 4, 6, 7};
    int size = sizeof(arr) / sizeof(int);
    printf("\nSize = %d",size); // resulting right value
    doStuff(arr);
}
void doStuff(int arr[]){
    int size = sizeof(arr) / sizeof(int); // resulting 1
    printf("\ndoStuff::Size = %d",size);
}

Output:

Size = 6
doStuff::Size = 1

The "size" value is displaying right. But, why doStuff::Size is 1 ?
Although, I'm using the same concept in both the functions the difference is only the parameterized array.
Please give your suggestions or correct the mistake if I've done any.

  • It loses the size information when passed into a function. If you wrap the array in a struct then you can get the size in the function as well. – clcto Oct 26 '14 at 20:47
  • 1
    Have you searched for existing questions about this problem? I have doubts that you are the first person ever to encounter this. – Kerrek SB Oct 26 '14 at 20:48
  • I've encountered many questions. But, nothing was as similar what I observed. – Hitesh Kumar Oct 26 '14 at 20:52

1 Answers1

1

When an array is passed to a function, it gets coverted into a pointer to its first element. So what you do inside your function is essentially equivalent to:

int size = sizeof(int*) / sizeof(int); // resulting 1

If you want to pass size, pass it as another argument to the function.

For example,

void doStuff(int arr[], size_t size){
..
}

and call the function as:

doStuff(arr, size);

You should really be using size_t for as sizeof operator returns a size_t which may be larger than an int.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Thanks a lot for such a quick response and much detail information. Presently, I'm working on this approach what you said. as @clcto said that "wrap the array in struct". I'll give it a try. Is there any other way apart from the directly passing the size as param? – Hitesh Kumar Oct 26 '14 at 20:53
  • No. The size information of array is lost in a function if you pass the array. So you have to pass in one way or other (another argument, global variable, as a member of the array itself -- e.g. 1st element or last element). Wrapping an array in a struct is one approach so that you can pass the struct by value. – P.P Oct 26 '14 at 21:37
  • Thanks for your inputs and observation. Got it. – Hitesh Kumar Oct 26 '14 at 21:47