Solved

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

Posted on 1998-10-30
12
233 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
  • 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
 
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

744 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now