我尝试应用其他线程关于 EXC_BAD_ACCESS 消息的建议,但没有成功。该注释出现在 Node Create_Child (Node Parent_Node, int item) {
旁边。
typedef struct {
int Win_Loss;
int parent;
int identifier;
int Object_Moved;
int Wolf;
int Goat;
int Salad;
int Boat;
} Node;
Node Create_Child (Node Parent_Node, int item) {
Node Child;
Child.Boat = (-1)*Parent_Node.Boat;
Child.Wolf = Parent_Node.Wolf;
Child.Goat = Parent_Node.Wolf;
Child.Salad = Parent_Node.Salad;
int* Child_Items[] = {&Child.Wolf, &Child.Goat, &Child.Salad, &Child.Boat};
Child.parent = Parent_Node.identifier;
Child_Items[item][0] *= (-1);
Child.Object_Moved = item;
return Child;
}
有什么见解吗?内存分配似乎不是问题,但我可能没有看到任何东西。
最佳答案
指针例如Child.Wolf 是函数的本地,它们在您的 Create_Child
函数之外没有任何意义,但您将这些地址分配给 Child.Object_Moved
并返回它的副本。
您应该在堆上分配 Child
Node* Create_Child(Node Parent_Node, int item) {
Node* Child = malloc(sizeof(Node));
Child->Boat = -1*Parent_Node.Boat;
...
int* Child_Items[] = { &Child->Wolf, .. };
此外,最好对函数的所有参数进行健全性检查
在使用它们之前。例如item
在范围内?,Parent_Node
信息有效吗?
关于c - EXC_BAD_ACCESS 创建子节点(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32263262/