0
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?

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • 3
    Possible duplicate of [Is segfault guaranteed when dereferencing null pointer (C/C++)](https://stackoverflow.com/questions/46104370/is-segfault-guaranteed-when-dereferencing-null-pointer-c-c) – rsjaffe Nov 18 '18 at 16:05

1 Answers1

2

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>>.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • for i < 48 and with initializing masks as you put in your question? – Matthieu Brucher Nov 18 '18 at 15:26
  • You have to create a new `avail` for each entry in the mask "array". – Matthieu Brucher Nov 18 '18 at 15:30
  • Thanks I thought you had to remove the second masks and replace it with yours. I needed both. Can you explain to me why I need to do the line you mentioned. Why did I need to create 3 seperate "new" statements. Btw my program is now working but I am kind of confused how ! – pootispencerhere Nov 18 '18 at 15:32
  • 1
    You need to allocate `n`, because it's an object you need, you need to allocate your arrays of pointers `masks`, and then you need to allocate the objects that your pointers (from `masks`) are going to point to. And obviously use smart pointers and containers instead, seems like you are not handling memory management properly :/ – Matthieu Brucher Nov 18 '18 at 15:34
  • Nah I am trying to make the program play against me and it needs to search all possible positions as fast as it can in as less time as it can. using anding with the(1kb! of masks) will reduce complexity to 0(1) i think. so I need all the masks till the end of the program and in the long run its faster. Thanks for the quick answer! – pootispencerhere Nov 18 '18 at 15:38