+ 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 ?

8th Mar 2022, 8:48 AM
Sanjay Kamath
Sanjay Kamath - avatar
4 Answers
+ 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.
8th Mar 2022, 9:29 AM
HungryTradie
HungryTradie - avatar
+ 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.
31st May 2022, 11:19 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 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?
8th Mar 2022, 9:10 AM
Ipang
+ 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
8th Mar 2022, 12:37 PM
Sanjay Kamath
Sanjay Kamath - avatar