问题标题可能有点令人困惑,但我不想让它变得太长。那么问题来了:
我有一个带有计数器的结构。
typedef struct location{
int count;
char *name;
arc *arcs[10];
}location;
我正在尝试增加此计数器,将其用作数组的索引。
current->locptr->arcs[current->locptr->count] = malloc(sizeof(arc));
current->locptr->count++;
current是链表结构的节点,locptr是位置结构,arcs[]是弧结构数组。
这可能吗?我的代码每次在 malloc 行都会崩溃。
提前致谢!
编辑:其他结构
/*
* Arc lengths to and from locations. Has a name, and a number.
*/
typedef struct arc{
int cost;
char *to;
char *from;
}arc;
/*
* Location struct that can point to up to 10 other locations.
* This struct also contains the name of the establishment.
*/
typedef struct location{
int count;
char *name;
arc *arcs[10];
}location;
/*
* Linked list that contains a pointer to the location struct.
*/
typedef struct node{
struct node *next;
location *locptr;
}node;
最佳答案
malloc(sizeof(arc));
可能有问题。完成后:
arcs[i]=malloc(sizeof(arc));
您可能没有为 to
和 from
分配内存,即:
arcs[i]->to=malloc(length_you_want*sizeof(char))
arcs[i]->from=malloc(length_you_want*sizeof(char))
如果没有为结构体中的任何指针动态分配内存,则无法使用它们。因此,您还需要检查 location
中的 char *name;
。
注意: sizeof(char) 几乎总是 1,因此您可以省略它,或者可以尝试使用 malloc(length * sizeof *ptr)
样式来考虑可移植。
关于c - 我试图从数组中查找一个值,其索引是结构中的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806290/