简体   繁体   English

为什么我不能为指向null的指针设置数据值

[英]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.

相关问题 为什么 delete 不设置指向 NULL 的指针? - Why doesn't delete set the pointer to NULL? C ++-检查指针是否指向有效内存(此处不能使用NULL检查) - C++ - Check if pointer is pointing to valid memory (Can't use NULL checks here) 如何使用它指向的指针将指针传递给指向 function 的指针? - How can I pass a pointer to pointer to a function using the pointer it is pointing to? 当结构增长时,指向向量中元素的指针被设置为 NULL - Pointer pointing to an element in a vector gets set to NULL when the structure grows 如何将指向数组的指针初始化为数组中所有索引的空值 - How to initialize a pointer pointing to an array to null values for all index in the array 为什么不能在之后设置 const 指针? - Why can't a const pointer be set afterwards? 为什么 C++ 编译器不能知道指针指向派生的 class? - Why can't C++ compiler know a pointer is pointing to a derived class? 指向派生类的基类指针不能访问基类的公共数据成员吗? - Can't a base class pointer which is pointing to derived class access the public data members of base class? 我可以获取指向nullptr的指针的指针吗? - Can I get a pointer to a pointer pointing to nullptr, is it valid 无法访问/设置空结构的值 - Can't access/set values of a null struct
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM