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

前端 未结 5 1515
情歌与酒
情歌与酒 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: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.

提交回复
热议问题