C++ c++;使用foreach使数组为null Node*节点[3]; 用于(节点*每个节点:节点){ eachNode=0;//如果我尝试取消引用,它会给出seg fault }//例如*eachNode=0; if(节点[0]==0){ 我认为你应该试试: Node* nodes[3]; for (Node* eachNode:nodes) { eachNode = 0; //if i try to dereference it gives seg fault } // eg. *eachNode = 0; if (nodes[0] == 0) { cout << "Null"; } else cout << "Not null"; cout << '\n'; Node* nodes2[3]; for (int i = 0; i < 3; ++i) { //this way works fine nodes2[i] = 0; } if (nodes2[0] == 0) { cout << "Null"; } else cout << "Not null";
通过这种方式,您可以获得一个与值相反的引用,并且可以将其适当地设置为C++ c++;使用foreach使数组为null Node*节点[3]; 用于(节点*每个节点:节点){ eachNode=0;//如果我尝试取消引用,它会给出seg fault }//例如*eachNode=0; if(节点[0]==0){ 我认为你应该试试: Node* nodes[3]; for (Node* eachNode:nodes) { eachNode = 0; //if i try to dereference it gives seg fault } // eg. *eachNode = 0; if (nodes[0] == 0) { cout << "Null"; } else cout << "Not null"; cout << '\n'; Node* nodes2[3]; for (int i = 0; i < 3; ++i) { //this way works fine nodes2[i] = 0; } if (nodes2[0] == 0) { cout << "Null"; } else cout << "Not null";,c++,arrays,foreach,null,C++,Arrays,Foreach,Null,通过这种方式,您可以获得一个与值相反的引用,并且可以将其适当地设置为nullptr 我在C++ 11中没有太多经验,但是我有一个关于这个新的范围构造的更多信息的阅读。 < P>我相信你应该尝试: Node* nodes[3]; for (Node* eachNode:nodes) { eachNode = 0; //if i try to dereference it gives seg fault } // eg. *eachNode = 0; if
nullptr
<>我在C++ 11中没有太多经验,但是我有一个关于这个新的范围构造的更多信息的阅读。 < P>我相信你应该尝试:
Node* nodes[3];
for (Node* eachNode:nodes) {
eachNode = 0; //if i try to dereference it gives seg fault
} // eg. *eachNode = 0;
if (nodes[0] == 0) {
cout << "Null";
} else
cout << "Not null";
cout << '\n';
Node* nodes2[3];
for (int i = 0; i < 3; ++i) { //this way works fine
nodes2[i] = 0;
}
if (nodes2[0] == 0) {
cout << "Null";
} else
cout << "Not null";
通过这种方式,您可以获得一个与值相反的引用,并且可以将其适当地设置为nullptr
我在C++ 11中没有太多经验,但是我确实有过阅读更多关于这个新的范围构造的信息。
指针是按值传递的。所以设置<代码> EACHORTER=0;< /C> >将改变值,否则您试图取消不是指针的SONEY事件。指针是按值传递的。achNode=0;将更改该值,否则您将尝试取消对非指针的引用。
您在数组值上编写的循环:for(Node *&eachNode : nodes) {
eachNode = nullptr;
}
上述循环也可以使用auto
编写:
for (Node* eachNode:nodes) {
eachNode = 0;
}
上述循环的问题在于,eachNode
不是存储在数组中的指针,而是存储在循环局部变量中的指针的副本
如果希望将节点设置为null,则需要对要设置该节点的内存位置的引用。可以使用auto&
引用数组元素来获得该引用:
for (auto eachNode:nodes) {
eachNode = 0;
}
最后一段可能会执行您想要的操作。您编写的循环在数组的值上循环:
for(Node *&eachNode : nodes) {
eachNode = nullptr;
}
上述循环也可以使用auto
编写:
for (Node* eachNode:nodes) {
eachNode = 0;
}
上述循环的问题在于,eachNode
不是存储在数组中的指针,而是存储在循环局部变量中的指针的副本
如果希望将节点设置为null,则需要对要设置该节点的内存位置的引用。可以使用auto&
引用数组元素来获得该引用:
for (auto eachNode:nodes) {
eachNode = 0;
}
最后一段很可能会满足您的要求。您是对的。如果为nullptr,我仍然使用0,因为我想了解它的错误原因,但我将(Node*eachNode:nodes){eachNode=0;}改为(Node*&eachNode:nodes){eachNode=0;}现在它们都是空的。thanks@james1194430如果您觉得答案合适,请务必接受它。:)更惯用的用法是
for(auto&node:nodes)node=0;
您是对的。如果为null ptr,我仍然使用0,因为我想了解它的错误原因,但我将(node*eachNode:nodes){eachNode=0;}改为for(Node*&eachNode:nodes){eachNode=0;}现在它们都为null。thanks@james1194430如果您认为答案合适,请确保接受该答案。:)对于(auto&node:nodes)node=0;