+ 1
Initializing 0 depth arrays in C++
Which is the best way of initializing a 0 depth array [] , {0} or [ ] in C++ or any other ?
4 Réponses
+ 2
Don't we still need to have 1 space for \0 in an empty array? Don't you want to have your array initialised to your expected data size, and filled with \0 until used? Are you trying to do dynamic array with pointers? If an array pointer isn't assigned but gets used (still pointing to NULL) it can crash your program/computer/reality (very bad, pink elephants might arrive 🤯).
You shouldn't need to use the C words: malloc, calloc, realloc, free.
I think in C++ you use new, del. But I'm not 100% on that yet.
+ 2
int arr[ 8] = new int {0};
When you specify the size of an array, with a zero value, then the assignment becomes an empty array.
The new keyword ensures that the array exists as an instance, and the requisite space can be allocated, and deallocated, as and when necessary.
+ 1
Why are you creating an array when it's reserved for zero element (with nothing in there)?
In C++ some compiler doesn't accept a request for creating empty array (including one in SoloLearn).
I mean, why bother initializing when there was nothing to initialize?
+ 1
Jay Matthews Yes now I remember..
sizeof operator gives the size of each element in bytes, which depends on the type of the array, viz. String / Integer