为什么这种初始化不起作用?

时间:2023-02-04 21:40:52

I have a struct called Node. Node accepts a double and stores it into a variable named value.

我有一个名为Node的结构。 Node接受double并将其存储到名为value的变量中。

I'm trying to make a new struct. My first example works, but the second doesn't. The second example doesn't give a compiler error and it builds just fine, but when I try to access a value from the node later on, it gives me -9.25596e+061.

我正在尝试制作一个新结构。我的第一个例子有效,但第二个例子没有。第二个例子没有给出编译器错误,它构建得很好,但是当我稍后尝试从节点访问一个值时,它给了我-9.25596e + 061。

This code works fine:

这段代码工作正常:

Node *firstNode; 
Node *newNode = new Node(value); 
firstNode = newNode; 

This code doesn't:

此代码不:

Node *firstNode; 
Node newNode(value); 
firstNode = &newNode;

I could just use the first three lines of code, but I want to know why the other code doesn't work. Is it fundamentally wrong or is the syntax just slightly off?

我可以使用前三行代码,但我想知道为什么其他代码不起作用。这是根本错误还是语法略有偏差?

1 个解决方案

#1


3  

Local variables are automatic - they go out of scope when the function returns and any further access to them (like via pointers as you did) is undefined behavior.

局部变量是自动的 - 当函数返回时它们超出范围,并且对它们的任何进一步访问(如通过指针一样)是未定义的行为。

new allocates memory on the free store, which is independent of scopes or lifetimes. It can only be freed by delete or by the OS when the program exits.

new在免费商店上分配内存,这与范围或生命周期无关。它只能在程序退出时通过删除或操作系统释放。

#1


3  

Local variables are automatic - they go out of scope when the function returns and any further access to them (like via pointers as you did) is undefined behavior.

局部变量是自动的 - 当函数返回时它们超出范围,并且对它们的任何进一步访问(如通过指针一样)是未定义的行为。

new allocates memory on the free store, which is independent of scopes or lifetimes. It can only be freed by delete or by the OS when the program exits.

new在免费商店上分配内存,这与范围或生命周期无关。它只能在程序退出时通过删除或操作系统释放。