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

C++ Counting number of elements an array can hold

Hi I'm trying to get some skills in C++.  I'm a total newbie here.  So I'm trying to write a function that will count the number of elements that an array can hold without using a variable to hold this number.

I know in java I could say something like  array.length();  I think this is also possible in C++, something like sizeof *array, but is there a way to calculate the size of the array without using sizeof or using a variable to hold the number?

  • 2
2 Solutions
the sizeof() function can return the size of a varible,
    if it is array it returns the total size
    for example if you take a array int arr[10];
    printf("%d",sizeof(arr)); this returns 40 (it is compiler dependent)
    if you divide the size 40 by the size of a int value
    ie 40/4 =10 which gives the total elements that is the lenght of the array

int array[20];
int GetArrayLength(int array[])
return sizeof array / sizeof array[0];

Open in new window


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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