[英]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
现在说我必须设置一些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
. 我收到一个错误nullptr
。 If I do nothing to set pointer I get Access Violation
. 如果我不做任何设置指针的操作,则会出现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? 如果我只想设置其数据,该将其指向何处?
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>>
. 似乎masks
应该是std::vector<std::unique_ptr<avail>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.