By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,949 Members | 946 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,949 IT Pros & Developers. It's quick & easy.

Finding size of an integer array after the array has been passed to a function

P: n/a
Expand|Select|Wrap|Line Numbers
  2. #include<iostream>
  3. using namespace std;
  5. class Test 
  6. {
  7. public:
  8.     void search(int arr[]) {
  9.         int count=0;
  10.         int size=(sizeof arr/sizeof arr[0]);
  11.         cout << "In search function, size = " <<size<<endl;
  12.         cout << "In search function, sizeof arr = "<<sizeof arr<<endl;
  13.         cout << "In search function, sizeof arr[0] = "<<sizeof arr[0]<<endl;
  14.     }
  15. };
  17. void main () 
  18. {
  19.     int arr1[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
  20.     int siz=(sizeof arr1/sizeof arr1[0]);
  21.     cout << "In main, size = " <<siz<<endl;
  22.     cout << "In main, sizeof arr1 = " <<sizeof arr1<<endl;
  23.     cout << "In main, sizeof arr1[0] = " <<sizeof arr1[0]<<endl;
  24.     Test obj;
  26.     cin.get();
  27. }
I am trying to find the size of an array after it is passed into a function. I used the sizeof operator. It displays the correct information in the main function, but as soon as I pass the array to a different function, it doesn't print the correct values. How do I fix this? Thanks.
Sep 28 '10 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 983
Use template vectors.

Basically the main function knows the size of the array, because it is instantiated there.

In your method search(), all the compiler knows is that it has an indefinite size array.

In C++ (and C) the compiler silently coerces indefinite array definitions into pointers when they are used as part of a function or method's argument list.

Expand|Select|Wrap|Line Numbers
  1. void function(double f[])
silently becomes

Expand|Select|Wrap|Line Numbers
  1. void function(double *f)
and thus (on most compilers) the sizeof f will be four.

Sep 28 '10 #2

Expert Mod 5K+
P: 9,197
sizeof returns the size of the item on the stack.

Therefore, sizeof a local array will produce the correct result.

However, when an array is passed to a function, what is passed is the address of element 0. Therefore, inside the function, sizeof is reporting the size of the address and not the size of the array.

This is called decay of array.

The usual practice is to pass additional argument(s) for the number of elements.
Sep 28 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.