我的代码如下。在标有*
的行上,我得到:
error: expected expression before ‘{’ token
rval.adj_list[0] = { {"B","C",3},{"B","A",2} };
是否有一种简洁的方法来初始化指向指针的动态分配“双数组”?
struct node;
struct edge {
char *from;
char *to;
int weight;
};
struct digraph {
char **vertices;
struct edge **adj_list;
};
int main( int argc, char *argv[] ) {
struct digraph rval;
int size = 5;
rval.vertices = malloc( size * sizeof(char*));
rval.adj_list = malloc( size * sizeof(struct edge*));
rval.vertices[0] = "A";
rval.adj_list[0] = { {"A","B",2},{"A","E",1} }; //********
rval.vertices[1] = "B";
rval.adj_list[1] = { {"B","C",3},{"B","A",2} }; //********
rval.vertices[2] = "C";
rval.vertices[3] = "D";
rval.vertices[4] = "E";
}
答案 0 :(得分:3)
你需要一个C99'复合文字',它看起来像一个演员,然后是大括号中的初始化器。
rval.adj_list[0] = (struct edge []){ {"A","B",2},{"A","E",1} };
这导致:
#include <stdlib.h>
struct node;
struct edge {
char *from;
char *to;
int weight;
};
struct digraph {
char **vertices;
struct edge **adj_list;
};
int main(void)
{
struct digraph rval;
int size = 5;
rval.vertices = malloc( size * sizeof(char*));
rval.adj_list = malloc( size * sizeof(struct edge*));
rval.vertices[0] = "A";
rval.adj_list[0] = (struct edge[]){ {"A","B",2}, {"A","E",1} };
rval.vertices[1] = "B";
rval.adj_list[1] = (struct edge[]){ {"B","C",3}, {"B","A",2} };
rval.vertices[2] = "C";
rval.vertices[3] = "D";
rval.vertices[4] = "E";
}
答案 1 :(得分:2)
您只能在(struct edge[])
之前以C99模式初始化整个结构。否则,您必须自己初始化每个成员:
rval.adj_list[0] = (struct edge[]){ {"A","B",2}, {"A","E",1} };
...
rval.adj_list[1] = (struct edge[]){ {"B","C",3}, {"B","A",2} };
或者:
rval.vertices[0] = "A";
rval.adj_list[0][0].from = "A";
rval.adj_list[0][0].to = "B";
rval.adj_list[0][0].weight = 2;
rval.adj_list[0][1].from = "A";
rval.adj_list[0][1].to = "E";
rval.adj_list[0][1].weight = 1;
rval.vertices[1] = "B";
rval.adj_list[1][0].from = "B";
rval.adj_list[1][0].to = "C";
rval.adj_list[1][0].weight = 3;
rval.adj_list[1][1].from = "B";
rval.adj_list[1][1].to = "A";
rval.adj_list[1][1].weight = 2;