#dynamic arrays
43 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
How can one initialize a dynamic array with a nullptr.
;compile
#include <memory>
std::unique_ptr<int[]> darray(nullptr);
darray[0] = 0x100;
Program terminated with signal: SIGSEGV
Is this what you did?
used raw pointers
int* p = new int[5];
p = nullptr;
p[0] = 1;
i mean initializing a normal array with 0 then assigning a value let's you access the elements again
new int[5] returns a pointer to the beginning of the heap allocated memory that you binded to p, but then you reassigned THAT pointer object p to nullptr, this is wrong
hehe
so I'm better off just initializing with 0
so when exactly is nullptr necessary
if you are using C++ don't use raw pointers for arrays, either use std::array if you know the size before-hand or an std::vector (if you want it to resize automatically as you add elements)
personally i will never recommend you to use nullptr in modern C++ now, if you want to indicate that a value might be absent then use an std::optional instead
this is a better practice
nullptr the word is self explanatory, you use it when you want a pointer to hold no address.
thx I'll look into that
so one nullptr is used it can't hold an address during program flow again ?
It can, you just reassign the pointer a new value.
it can, nullptr is just a value that you assigned to a variable of pointer type
like any variable it can be reassigned
if the pointer points to memory that you don't have access to, like nullptr "does", and you try to access that memory anyway, like a pointer dereference or an array subscript do, segfaults are what you get
I think you're misunderstanding the purpose of nullptr, when a pointer is not pointing to an object it has nullptr as it's value, you then assign it a valid value by giving it an address of an object.
i think i get it now
(it can have a garbage value I'm aware)
Thank you and let us know if you have any more questions!
This thread is now set to auto-hide after an hour of inactivity
yeah it is indeterminate and dereferencing this pointer is an undefined behavior
Your name has enough explaination 😆
true
just gonna avoid using em
good 👍
just to add my two cents: as others have said you should avoid manually allocating memory, there are smart pointers for that for 99% of cases
using raw pointers is OK as long as you know what you're doing
and the modern way to use arrays in C++ is through std::array
std::array requires a complie time constant, this question is about dynamic arrays ...
my bad
i mentioned both here
hmmmm my wording is a bit wrong though, should have said that the size must be a "compile time constant" rather than "know the size beforehand"