c - 我试图从数组中查找一个值,其索引是结构中的计数器

标签 c arrays struct

问题标题可能有点令人困惑,但我不想让它变得太长。那么问题来了:

我有一个带有计数器的结构。

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));

您可能没有为 tofrom 分配内存,即:

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/

相关文章:

c - 根据优先级,后缀增量的优先级高于 <= 为什么我得到输出为 5

PHP按字段名对多维数组进行排序

python - 编写 Cython 扩展 : how to access a C struct internal data from Python?

c - 返回一个指向结构体的指针,该结构体中有一个 char ** 指针到指针

c# - 为什么有些方法对可空结构的空值起作用而有些方法不起作用?

c - 我收到运行时错误 : Segmentation Fault (SIGSEGV),,为什么?

c - 警告 : assignment makes integer from pointer without a cast in array

c - c 中的二叉树 -> 在深度超过 7 时崩溃

javascript - jquery 不发布数组数据

javascript - 一个很好的 JavaScript 来从/到数组添加/删除项目?