[英]C++ Struct pointers in linked list implementation
Could anyone help with this (I guess pointer and memory allocation problem-- At run time the code does not work if I remove the //COMMENTED// cout statement
The two *in
and *out
of struct data structure E although treated in the same manner, only the *in gives me the output as desired 任何人都可以帮助解决这个问题(我猜想是指针和内存分配问题-如果我删除了
//COMMENTED// cout statement
,则在运行时该代码将无法正常工作,尽管结构数据结构E中的两个*in
和*out
虽然已在以同样的方式,只有* in给我所需的输出
struct V
{
int al;
V *next;
};
struct E
{;
int id;
V *in;
V *out;
};
void init(E *edges, int count)
{
int i = 0;
int id = 1;
while (i < count)
{
edges[i].id = id;
edges[i].out = new V;
edges[i].out->al = 0;
edges[i].out->next = NULL;
edges[i].in = new V;
edges[i].in->al = 0;
edges[i].in->next = NULL;
i++; id++;
}
i =0;
while (i < count)
{
cout<<"Edges are:"<<endl;
cout<<"Edge In "<<i<<" is "<<edges[i].in->al<<endl;
//cout<<"Edge Out "<<i<<" is "<<edges[i].out->al<<endl;
i++;
}
}
int main()
{
int counter=5;
E *edges = new E[counter];
init(edges,counter);
}
See this line 看到这条线
edges[i].id = ++i;
You are changing i
, but then continue to use it for your later statements. 您正在更改
i
,但是在以后的语句中继续使用它。 This will leave some of your elements uninitialized and others will try to write outside of your array boundaries. 这将使您的某些元素未初始化,而其他元素将尝试在数组边界之外进行写入。
Edit: As Deduplicator points out, this is undefined behavior (UB) even before it gets to the next statement. 编辑:正如Deduplicator指出的那样,即使到达下一条语句,这也是未定义的行为(UB)。 You can't rely on which order the left and right hand sides of the assignment operator are evaluated, so (for example) the
i++
might happen before the edges[i]
part. 您不能依赖于赋值运算符左侧和右侧的评估顺序,因此(例如)
i++
可能在edges[i]
部分之前发生。 This question has some informative answers. 这个问题有一些有益的答案。
This line has a bug: edges[i].id = ++i;
这行有一个错误:
edges[i].id = ++i;
Here array element at index 1 is getting assigned instead of intended element at 0 index. 在这里,索引1处的数组元素被分配,而不是索引0处的预期元素。 Change it to something like:
edges[i].id = i+1;
将其更改为以下内容:
edges[i].id = i+1;
and increment i
at the end of while loop. 并在while循环结束时增加
i
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.