what is the default value of an array in C++?

前端 未结 5 1379
情歌与酒
情歌与酒 2021-01-06 09:12

If I were to create an array with int* array = new int[10]; and fill part of the array with values, how can I check how much of the array is filled? I want to l

相关标签:
5条回答
  • 2021-01-06 09:17

    You can solve your problem by a more C++ way. You can create struct or class, which contain your value and bool flag. Bool flag must be set to false in default constructor and set to true in operator=. There is ready implementation of such class - boost.optional. std::optional will be in C++17.

    #include <boost/optional.hpp>
    #include <iostream>
    
    int main()
    {
        const size_t nArr = 100;
        auto pArr = new boost::optional<int>[nArr];
        const size_t nInit = 30;
        for (size_t i = 0; i < nInit; ++i)
        {
           pArr[i] = i;  //initialize nInit first values of pArr
        }
        size_t n = 0;
        for (; n < nArr; ++n)
        {
             if (!pArr[n].is_initialized()) break;
             // or more compact form:
             //if(!pArr[n]) break;
             assert(*pArr[n] == n);
        }
        std::cout << "nInit = " << nInit << ", n = " << n << std::endl;
        assert(nInit == n);
        delete[] pArr;
    }
    
    0 讨论(0)
  • 2021-01-06 09:26

    The default value of array is indeterminate means garbage.

    how can I check how much of the array is filled?

    You cannot check, C/C++ has no array bounds check. You have to do it yourself.You need to keep track of the data inserted by a user. When your counter reaches the size of the array, the array is full

    0 讨论(0)
  • 2021-01-06 09:31

    You can't do what are you hoping to, not when the type is int.

    The uninitialized elements of the array will have unpredictable values. In addition, accessing those elements is cause for undefined behavior.

    You can initialize the elements of the array to a sentinel value at the time of allocation using:

    int* ptr = new int[10]{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
    

    Use whatever sentinel value works for you if -1 does not.

    0 讨论(0)
  • 2021-01-06 09:34

    This is how to set a default value in C++ when making an array.

    int array[100] = {0};
    

    Now every element is set to 0. Without doing this every element it garbage and will be undefined behavior if used.

    Not all languages are like this. Java has default values when declaring a data structure but C++ does not.

    0 讨论(0)
  • 2021-01-06 09:38

    There is no default value so it's garbage.

    0 讨论(0)
提交回复
热议问题