Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to find the size of array after being pass into a function?

Posted on 1998-10-30
12
Medium Priority
?
255 Views
Last Modified: 2010-08-05
How do I get the size of an array passed to a function.
The usual way of sizeof array / sizeof array[0] doesn't work inside the body of a function after it is passed to a function.
Any thought? Preferrably as simple as possible, thanks
0
Comment
Question by:hshliang
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +5
12 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 1176629
pass the size to the function
0
 
LVL 6

Expert Comment

by:thresher_shark
ID: 1176630
That's what I would do, I don't think there is any other way.  If the array is an integer, then you might be able to even store the size of the array in the first array element.
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1176631
Or you could use a sentinel value in your arrays like strings do.

These I believe are your only three possible alternatives.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 12

Expert Comment

by:rwilson032697
ID: 1176632
ozo is right - passing the size of the array is your best option.

Raymond.
0
 
LVL 8

Expert Comment

by:Answers2000
ID: 1176633
(1)when you pass an a traditional array, it gets converted to a pointer to the start of the array, hence the need to pass number of items separately as everybody else said ?

But hey this is a C++ page - why not use - one of
(2) pass CArray (MFC) reference
(3) pass vector (STL) referene

Here's examples of each

void Func1A( int x[], int size )
{
 // separate size required
}

void Fun2A( /*const*/ CArray<int,int>& array )
{
// get size use GetUpperBound / GetSize member functions of CArray
// [MFC CArray supports array large than the number of elements for speed- ups]
}


void Func3A(( /* const */ vector<int>& array )
{
// arrray size given by array.size()
}


0
 

Author Comment

by:hshliang
ID: 1176634
Thank you for all your answers. This reconfirms my belief that there is no other simpler way as suggested by all of you. The reason I ask is I am wrtting a function with many arguments, and if I can save one argument, it will make it look clearer. And I don't want to pass a CObject (like CArray) which comes with a large overhead and needs more steps to set up. Tahnk you all for your prompt response.
Henry
0
 
LVL 5

Expert Comment

by:yonat
ID: 1176635
You wrote:
>>>>>
I don't want to pass a CObject (like CArray) which comes with a large overhead and needs more steps to set up
<<<<<

So pass a "small" object. Something like

template <class E>
class Array
{
public:
      // Construction and destruction
      Array() : itsSize(0), itsElements(0) {}
      ~Array() {delete itsElements;}
      Array(size_t size) : itsSize(0), itsElements(0)
      {
            itsElements = new E(size);
            itsSize = size;
      }
      Array(const Array& r) : itsSize(0), itsElements(0) {copy(r);}
      Array& operator=(const Array& r)
      {
            if (this != &r) {
                  delete itsElements;
                  copy(r);
            }
            return *this;
      }

      // Accessors and mutators
      T& operator[](size_t index] {return itsElements[index];}
      const T& operator[](size_t index] const {return itsElements[index];}
      size_t GetSize() const {return itsSize;}

private:
      size_t itsSize;
      E* itsElements;

      void copy(const Array& r);
      {
            itsElements = new E(r.itsSize);
            for (size_t i = 0; i < r.itsSize; ++i)
                  itsElements[i] = r.itsElements[i];
            itsSize = r.itsSize;
      }
};

Note: Check this code for typos before you use it.
0
 
LVL 5

Expert Comment

by:yonat
ID: 1176636
Jeez, all my nice identation vanished... Anyone know how to post code in a readable way?
0
 
LVL 10

Accepted Solution

by:
viktornet earned 100 total points
ID: 1176637
Hello guys.... Here is a way...

This is in C/C++ but I'm sure you'll be able to convert it since it's a few lines of code...

#include <iostream.h>
#include <conio.h>

typedef int int_arr[5];
int Get_Element_Num(int_arr Data);
void main()
{
  int_arr MyArr;
  clrscr();
  cout << "MyArr has " << Get_Elements_Num(MyArr) << elements!";
  getch();
}
int Get_Element_Num(int_arr Data)
{
  return sizeof(int_arr) / sizeof(int);
}

This something I wrote some while ago....

Cheers,
Viktor
0
 
LVL 8

Expert Comment

by:Answers2000
ID: 1176638
that's fine viktor except
1. you copy the entire array (into a temporary) for every function call...i wouldn't want to do this for a large array
2. in any case the array is always 5, and this is coded in the function at compile time.  [your function won't handle an array of any arbitary size - so doesn't really solve the problem in the general case]
0
 
LVL 10

Expert Comment

by:viktornet
ID: 1176639
You can use this declaration then....



   #include <iostream.h>
   #include <conio.h>

   typedef int int_arr[]; //Just know the data type... no matter what is the array....
   int Get_Element_Num(int_arr Data);
   void main()
   {
     int_arr MyArr;
     clrscr();
     cout << "MyArr has " << Get_Elements_Num(MyArr) << elements!";
     getch();
   }
   int Get_Element_Num(int_arr Data)
   {
     return sizeof(int_arr) / sizeof(int);
   }

Cheers,
Viktor
0
 

Author Comment

by:hshliang
ID: 1176640
These are all good suggestions, but the essence of my question is still for simple purpose that hopefully will need only one line of code. The reason I ask was to find a simple way to make sure the 3 long values passed to the function are valid. The easiest way is to pass 3 variables of long type, or an array of 3 longs. When I opt for the latter, I wanted to make sure exactly 3 elements are passed (not 1 or 2 which may crash as you will be assessing a non-existing variable). then I found there is no way to do it. Now I am back to passing 3 long arguments, though looks crumblesome, but simple (as compare to passing objects!).
Thanks everyone. :-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

704 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question