• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 12461
  • Last Modified:

Determining array length

Actually, this question has two parts.

1. Can C++ arrays only hold primitive types such as int, float, etc? Can it hold abstract types such as:

class A {

int main() {
    A a1, a2, a3;
    A a[] = {a1, a2, a3};
    myFunc(a); // see part 2
    return 0;

2. Now for my real question. When passed an array as a parameter, how do I determine the length of the array? This array contains abstract types.

From the example above, suppose I have the following function

void myFunc(A *x) {
// how do I find the length of the array

In C, I know that you can do the following

int size = sizeof(x) / sizeof(x[0]);

Thanks a lot everyone.

P.S. I am interested only in arrays. Not vectors.
1 Solution
1. If you are interested in arrays only.
One way would be to make it an array of pointers and hold the pointers to your abstract classes in the array
1. The answer is yes and no.

   you can't do  "AbsType name[10];"
   since you cannot define a variable of type with pure virtual methods

   You can do      AbsType *name = new ConcreteType[10];

2.  You cannot find the size of an array passed as a parameter.
You cannot even do that in C; the code you gave only works for
a static array (Yes, that code works for the same situation in C++ that
it works for in C).

f(int x[]) {
   return sizeof(x) / sizeof(x[0]);

Will always return  sizeof(int *) / sizeof(int)
which is not the size of the array passed.

In both C and C++

if you want to know the length, then you need to pass it, i.e.

f(int x[],  int numberElementsInArray)

In your example, you're passing a static array to your function.

If you're only going to be using static arrays, and the size is variable depending where it's being called, then you can determind the size of the array if you use a template function.

template<class T>
void MyFunc(T&Src)
      int Size = sizeof(Src)/sizeof(Src[0]);
      cout << Size << endl;

int main(int argc, char* argv[])
      int data1[5] = {1, 2, 3, 4, 5};

      int data2[10] = {1, 2, 3, 4, 5, 1, 2, 3, 4, 5};

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now