Best way to initialize a pointer array without knowing element size in advance

SOLVED

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
jedwardsol•
std::vector<int*>  arrPtr(studentNumber, nullptr);
7
IyeOnline•

Probably dont name it arrPtr (since its neither an array nor a pointer), but this is the proper way in modern C++.

8
ViewedFromi3WMOP•

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?

1
jedwardsol•

No, because what you've written isn't valid C++. C++ doesn't support variable length arrays.

But where they are allowed

int *arrPtr[studentNumber] = {0};

will zero-initialise it.

6
ViewedFromi3WMOP•

So I would have to dynamically allocate it then, and then do that you are saying?

1
jedwardsol•

Yes. You could use new and then a loop.

Or use std::vector (which behind the scenes uses new and a loop). Some advantages of the vector is that it doesn't forget to call delete, and it knows its size so it is easier to pass around to other functions.

6
[deleted]•

[deleted]

1
ViewedFromi3WMOP•

Thank you

1
rmoritz•

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.

1
ViewedFromi3WMOP•

Ok thank for you for both bits of advice. I needed that. Thank you.

1
khedoros•

If studentNumber isn'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 usual int* arrPtr = new int*[studentNumber]; /*bunch of code*/ delete[] arrPtr;, which is essentially how std::vector works anyhow.

1