我已经调试了这个函数很长一段时间了,无法解决这段代码可能发生的问题。
void make_points(DocSpec instance, Tree *myTree, Point *p){
int i, j, k, index = 0;
for(i = 0; i < instance.numPt; i++)
{
p[i].x = instance.xCoordinates[i];
p[i].y = instance.yCoordinates[i];
p[i].parent = myTree[i].parent;
p[i].num_children = 0;
for(k = 0; k < MAX_NUM_CHILDREN; k++)
{
p[i].child[k] = 0;
}
for(j = 0; j < instance.numPt; j++)
{
if((i != j) && (myTree[j].parent == i))
{
p[i].num_children++;
p[i].child[index] = j;
index++;
}
}
p[i].overlap_hv = -1;
p[i].overlap_vh = -1;
index = 0;
}
printf("p[1].index = %d;\n", p[1].index);
printf("p[1].x = %d;\n", p[1].x);
printf("p[1].y = %d;\n", p[1].y);
printf("p[1].parent = %d;\n", p[1].parent);
printf("p[1].num_children = %d;\n", p[1].num_children);
printf("p[1].child[8] = {");
index = 0;
for(i = 0; i < MAX_NUM_CHILDREN; i++)
{
if(p[1].child[i] != 0 && index == 0)
{
printf("%d", p[1].child[i]);
}
elseif(p[1].child[i] != 0)
printf(", %d", p[1].child[i]);
}
print("};\n");
printf("p[1].overlap_hv = %d;\n", p[1].overlap_hv);
printf("p[1].overlap_vh = %d;\n", p[1].overlap_vh);
}
运行该函数后我得到的输出如下:
p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {1563515760, 1768448814, 945513580, 540876893};
p[1].overlap_hv = 909455739;
p[1].overlap_vh = 892679225;
但它应该是:
p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {};
p[1].overlap_hv = -1;
p[1].overlap_vh = -1;
当我在我的程序上运行gdb时,我注意到p [1]的值被正确初始化,但是当
时printf("p[1].x = %d;\n", p[1].x);
被执行 - p [1] .child [4],p [1] .child [5],p [1] .child [6],p [1] .child [7],p [1] .overlap_hv,p [1] .overlap_vh都会被垃圾值覆盖。
我不知道printf语句为什么或如何更改我的struct成员的值。
非常感谢任何帮助。
答案 0 :(得分:0)
我的猜测是index
正越过子边界而j
会覆盖下一个结构成员p[1].overlap_hv
和p[1].overlap_vh
:
p[i].child[index] = j;
index++;
答案 1 :(得分:0)
事实证明,在重新分配内存时我没有使用正确的类型转换。与Valgrind的快速检查让我找到了罪魁祸首。
有
p = (Point*) realloc(p, instance.numPt * sizeof(p));
并修复了它
p = (Point*) realloc(p, instance.numPt * sizeof(Point));
感谢大家的建议。