okay i have an array of a struct.

struct MYSTRUCT
{
    float myFirstVal, mySecondVal, myThirdVal;
    unsigned char myByte;
}

int myCountFunction(MYSTRUCT *&myArrayOfStructs)
{
    int myCount;
    // question area
    return myCount;
}

here is my question. how do i count the number of elements in an array of type blah quickly. I have tried to "sizeof()" the array and only seem to get the size of the struct. I tried to "sizeof()" the reference and only get the size of the DWORD pointer. I thought that i could take the total size and divide that value by the size of the struct to get the elements... but this worked to no avail.

any help is much appreciated.
Thanks.

Recommended Answers

All 3 Replies

You will only be able to know the number of elements in the array in the function in which it is allocated. If created as a local array, say

int some_array[] = { 1,2,3,4,5,6,7,8};

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

will give you the number of elements. This only works in the function where allocated. As you've seen, when the array is passed to a function, only the data type and the address of first element is known there.

If you dynamically allocated the array, then at that point you know the number of elements.

Thus, you generally need to explicitly pass the size of the array, or the number of currently filled elements, to any function that must know this.

If you use the STL vector, it has a size( ) member that will tell you how big it is.

Is this an accurate example code creating the array and storing the arrays with at least 3 entries?
Constant Integer SIZE = 3
2. Declare Integer employeeIdNumber
3. Declare Real volunteerHours
4. Declare Integer index
5. For index = 0 to SIZE - 1
6. Display "Enter the ID Number of", index + 1
7. Input employeeIdNumber[index]
8. Display "Enter the number of Volunteer Hours that employee has worked."
9. Input volunteerHours[index]
10. End For
11. Display "Here are the Employee ID Numbers with the Volunteer Hours."
12.For index = 0 to SIZE -1
13.Display employeeIdNumber[index], ": " volunteerHours[Index]

Another vote for using std::vector instead of an array. It will save you countless headaches.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.