1

I realized that sizeof(arr)/sizeof(arr[0]) returns the size of the array and not the actual number of elements in the array.

   int main(void) 
{

    int a = 1;
    int b = 2;

    int arr[5] = {a, b};

    int arrcount = sizeof(arr)/sizeof(arr[0]);

    printf("Array Size: %d\n", arrcount);

    return EXIT_SUCCESS;

}

arrcount here equals to 5. Is there a way to get the number of elements equal 2 in this scenario without changing the array size?

8
  • 3
    Your array contains 1 2 0 0 0. The 0s still exist. Commented Apr 7, 2019 at 5:13
  • 1
    It's not clear what you mean by "the number of elements". There are five elements in that array. Do you mean the number of non-zero elements? Maybe you really want std::vector. Commented Apr 7, 2019 at 5:13
  • int arr[5] = {a, b}; just remove the 5 here. It is not required when you're assigning to an array literal. Commented Apr 7, 2019 at 5:15
  • 2
    The size of the array and the number of elements are the same. Arrays are fixed size containers. Commented Apr 7, 2019 at 5:17
  • Perhaps the container you're looking for is Boost's static_vector? Commented Apr 7, 2019 at 5:18

1 Answer 1

2

I realized that sizeof(arr)/sizeof(arr[0]) returns the size of the array and not the actual number of elements in the array.

When you say the actual number of elements in the array, I think you mean the number of elements that have been explicitly initialized to something other than zero.

The only way to to do that would be to iterate through the elements of the array and count the number of elements that pass a certain filter.

int count = 0;
for ( int item : arr )
{
  if ( item != 0 ) // This is a filter
    ++count;
}

The standard library provides a function for that, std::count_if.

int count = std::count_if(std::begin(arr), std::end(arr),
                          [](int item) -> bool { return item != 0; });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.