试图在C中取消引用/使用双指针

时间:2012-09-25 06:07:31

标签: c pointers dynamic-memory-allocation

所以我在使用/取消引用C中的双指针时遇到问题。它在非结构或联合的东西中给出了成员 * 的错误消息请求。现在,我看到许多帖子都有类似的问题但是,像(*head)head = &temp这样的解决方案不起作用。有人可以帮我吗?

vertex_t **create_graph(int argc, char *argv[]) {
   vertex_t **head, *temp;

   temp = malloc(sizeof(vertex_t));

   head = head->temp;
   head->name = argv[1];

   head->next = malloc(sizeof(vertex_t));
   head->next->name = argv[2];
   head->next->next = 0;

   head->adj_list = malloc(sizeof(adj_vertex_t));
   head->adj_list->edge_weight = atoi(argv[3]);
   head->adj_list->vertex = head->next;

   head->next->adj_list = malloc(sizeof(adj_vertex_t));
   head->next->adj_list->edge_weight = atoi(argv[3]);
   head->adj_list->vertex = head;

   return head;
}

2 个答案:

答案 0 :(得分:3)

那里的一切都说你应该使用vertex_t *head

此外,由于您尚未分配head = head->temp;head将崩溃。

答案 1 :(得分:-1)

这符合您的要求吗?

vertex_t **create_graph(int argc, char *argv[]) {
vertex_t *head, **temp;

head = malloc(sizeof(vertex_t));
temp = malloc(sizeof(vertex_t*));
*temp = head;

head->name = argv[1];

head->next = malloc(sizeof(vertex_t));
head->next->name = argv[2];
head->next->next = 0;

head->adj_list = malloc(sizeof(adj_vertex_t));
head->adj_list->edge_weight = atoi(argv[3]);
head->adj_list->vertex = head->next;

head->next->adj_list = malloc(sizeof(adj_vertex_t));
head->next->adj_list->edge_weight = atoi(argv[3]);
head->adj_list->vertex = head;

 return temp;
}