C++ Counting number of elements an array can hold

Posted on 2009-02-24
Last Modified: 2013-12-14
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?

Question by:ubuntuguy
    LVL 9

    Accepted Solution

    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
    LVL 9

    Assisted Solution


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

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Enabling OSINT in Activity Based Intelligence

    Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

    Suggested Solutions

    Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project ( automates most of the tasks discussed in this article. You can even fin…
    How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from ( Go to that link and select download selenium in the right hand columnThat will then direct you to their downlo…
    This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
    The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

    761 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

    8 Experts available now in Live!

    Get 1:1 Help Now