pootispencerhere
pootispencerhere

Reputation: 45

Why can't I set values of data for a pointer pointing to null

struct avail
{
    int value;
    uint64_t y[8][5];
    avail **masks;
};
avail *n = new avail;
n->masks = new avail*[48];

Now say I have to set some data of n->masks[i]->y[1][3]=0x000000000000000F

Why can't I do this if I do

n->masks[i]=NULL;

I don't want any hierarchy like linked list. I get an error nullptr. If I do nothing to set pointer I get Access Violation. Where should I point this pointer if I don't want to use its "links" to create any tree/hierarchy.

This only works if I set

n->masks[i]=n;

But I think this will overwrite data storage. Is there anything wrong with my implementation? Where should I point it if I just want to set its data?

Upvotes: 0

Views: 181

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

Because if the pointer is null, then you point to an address you can't write to. You can always write address you have allocated, stack or heap.

Allocate your masks, and then use it:

n->masks[i] = new avail;

But don't forget to delete the allocated objects. Seems like masks should be a std::vector<std::unique_ptr<avail>>.

Upvotes: 2

Related Questions