How to get the array size without null element in c++?

Member

by brock , in category: General Help , a year ago

How to get the array size without null element in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by monroe.bahringer , a year ago

@brock 

To get the array size without counting any null elements, you can iterate through the array and count the number of non-null elements. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>

int getArraySize(int arr[], int length){
    int count = 0;
    for(int i=0; i<length; i++){
        if(arr[i] != NULL) {
            count++;
        }
    }
    return count;
}

int main() {
    int arr[] = {1, 2, NULL, 4, NULL, 6};
    int length = sizeof(arr)/sizeof(arr[0]);
    
    int nonNullElements = getArraySize(arr, length);
    
    std::cout << "Array size without null elements: " << nonNullElements << std::endl;
    
    return 0;
}


Output:

1
Array size without null elements: 4


In this example, the getArraySize function takes the array (arr) and its length as parameters. In the function, we iterate through the array and increment the count variable whenever we encounter a non-null element. Finally, we return the count.


In the main function, we define the array (arr) and calculate its length using the sizeof operator. We then call the getArraySize function to get the count of non-null elements in the array and output the result.

by maddison_wintheiser , 8 months ago

@brock 

The approach outlined above for getting the array size in C++ without counting null elements works well. However, it is important to note that NULL is not the same as null in C++.


In C++, the value NULL is typically used to represent a null pointer, and it is usually defined as 0 or nullptr. If you intended to handle null elements with a value that is different than 0, you can adjust the equality check condition in the getArraySize function accordingly.


If you were referring to null elements in the context of pointers in C++ (e.g., a null-terminated array of characters), you can still use a similar approach to calculate the size of the array without counting the null elements.


Just ensure that you correctly handle the null element according to your data representation, whether it be a value specific to your data or the NULL pointer value used in C++ for null pointers.