Best way to initialize a pointer array without knowing element size in advance
So I’ll ask for a Number to be entered in to be the element size Then I’ll try to do what I can to assign all the elements to nullptr as they shouldn’t just not point to anything as we all know. But I feel like you guys know there’s a better way and that the time between initialization and then assigning nullptr via for loop is still technically wrong even if it’s the next step. Or.. maybe not
int *arrPtr[studentNumber];
for (int index = 0; index < studentNumber; index++)
arrPtr[index] = nullptr;
Posted Jul 23, 2020, 3:25 PM UTC
113
Probably dont name it
arrPtr(since its neither an array nor a pointer), but this is the proper way in modern C++.Looks good but just wondering is there a way to also do this with just normal arrays in case I need to use c language?
No, because what you've written isn't valid C++. C++ doesn't support variable length arrays.
But where they are allowed
will zero-initialise it.
So I would have to dynamically allocate it then, and then do that you are saying?
Yes. You could use
newand then a loop.Or use std::vector (which behind the scenes uses
newand a loop). Some advantages of the vector is that it doesn't forget to calldelete, and it knows its size so it is easier to pass around to other functions.[deleted]
Thank you
Go with the vector, but if you must:
int *arrPtr[studentNumber] = { nullptr };edit: This is not a good answer. as u/jedwardsol indicated, it's not ISO c++ - it's an extension supported by gcc and intel, but appears to not be by clang or msvc.
Ok thank for you for both bits of advice. I needed that. Thank you.
If
studentNumberisn't a constant there, then you're still using VLAs, which aren't valid C++, and are only supported as extensions within certain compilers (basically because it's valid in C, and it was easy to carry the feature over). You'd need to do the usualint* arrPtr = new int*[studentNumber]; /*bunch of code*/ delete[] arrPtr;, which is essentially howstd::vectorworks anyhow.