首页 > 解决方案 > C LinkedList 指针不适用于动态分配的数组

问题描述

我正在尝试使用指针分配 LinkedList 变量,但出现错误。这是我的代码。

typedef struct {
  struct Vertex *next;
} Vertex;
typedef struct {
  Vertex *vertices;
} Environment;
// here I dynamically allocate an array of vertexs, 28 to be specific
env->vertices = (Vertex *)malloc(7*sizeof(Vertex));
//this code is just to understand what I am trying to achieve
env->vertices[0].next = env->vertices[1];

我收到一条错误消息,提示我正在尝试将 Vertex 分配给 Vertex*。有任何想法吗?

标签: c

解决方案


传递地址正是您需要做的。您只是忘记了单词的一个实例Vertex。你的第一个声明应该是这样的:

typedef struct Vertex {
  struct Vertex *next;
} Vertex;

一旦你解决了这个问题,你就可以不用env->vertices[0].next = &env->vertices[1];不兼容的指针类型警告。


推荐阅读