#dynamic arrays

43 messages · Page 1 of 1 (latest)

floral cave
#

initialized a dynamic array with nullptr.
assigned values to elements but trying to access those elements returns a segmentation fault

chrome estuaryBOT
#

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.

lethal pilot
#

How can one initialize a dynamic array with a nullptr.

#

;compile

#include <memory>
std::unique_ptr<int[]> darray(nullptr);

darray[0] = 0x100;
charred juncoBOT
#
Compiler Output
Program terminated with signal: SIGSEGV
lethal pilot
#

Is this what you did?

floral cave
#
int* p = new int[5];
p = nullptr;
p[0] = 1;
lethal pilot
#

Well what else do you expect.

#

nullptr, Herald of Seg Faults

floral cave
#

i mean initializing a normal array with 0 then assigning a value let's you access the elements again

steady atlas
#

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

steady atlas
floral cave
#

so when exactly is nullptr necessary

steady atlas
#

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)

steady atlas
#

this is a better practice

lethal pilot
floral cave
lethal pilot
thorn rampart
#

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

lethal pilot
#

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.

floral cave
#

i think i get it now

lethal pilot
#

(it can have a garbage value I'm aware)

floral cave
#

thx

#

!solved

chrome estuaryBOT
#

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

steady atlas
lethal pilot
steady atlas
steady atlas
hasty coyote
#

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

oak cairn
hasty coyote
#

my bad

steady atlas
#

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"