C++ 如何设置数组指针的值
我试图给数组指针设置一个值,也将指针设置为NULL,但当我试图运行程序时,我得到了分段错误核心转储,我相信这是因为我在for循环中有什么。请帮忙C++ 如何设置数组指针的值,c++,arrays,pointers,C++,Arrays,Pointers,我试图给数组指针设置一个值,也将指针设置为NULL,但当我试图运行程序时,我得到了分段错误核心转储,我相信这是因为我在for循环中有什么。请帮忙 struct node { int value; node *next; }; int main(){ node **adj; int vert; cout<<"Please enter the number of vertices: "; cin>>vert; adj = new node* [vert-1]; fo
struct node {
int value;
node *next;
};
int main(){
node **adj;
int vert;
cout<<"Please enter the number of vertices: ";
cin>>vert;
adj = new node* [vert-1];
for (int x = 0; x <= vert-1; x++)//set all the names of the value.
{
adj[x]->value = x;
cout<< adj[x]->value;
adj[x] = NULL
}
return 0;
}
使用adj=新节点*[vert-1];只需为vert-1指针保留内存,但您正在为这些指针中的每个指针赋值,而不为它们保留内存
做你想做的事的正确方法是:
node * adj;
..
adj = new node[vert-1]; // reserv memory for all information
// EDITED for out of array bounds: thanks @Leiaz
for (int x = 0; x < vert-1; x++)//set all the names of the value.
{
// now, you can modify a reserved memory portion
adj[x].value = x;
adj[x].next = NULL;
}
您还必须执行adj[x]=新节点;在你的循环中。还有,coutname;,你是说coutname;“名称”是我使用的名称,但我将其切换为“值”,然后忘记了名称。@杰克惠瑟姆:谢谢,这很有效@JackWhitham请尝试将其发布为答案,而不是评论,如果您认为它解决了问题,请不要在您要求查找错误时更正代码中的错误。一旦你在你的问题中纠正了它们,当一个人不知道历史时,帮助你发现它们的答案/评论就会变得相当混乱->和有什么区别?adj[x]是一个节点,而不是指向节点的指针。正在使用..访问结构项。。使用->访问属于结构指针的项。阅读更多关于C/C++指针的内容。