Expected expression before ‘{’ token in trying to initialize array of array of structs
arrays, c
Solution
You'd need a C99 'compound literal', which looks like a cast followed by an initializer in braces.
rval.adj_list[0] = (struct edge []){ {"A","B",2},{"A","E",1} };
This leads to:
#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";
}
Problem
My code is below. On the lines marked with `*`'s, I get: ``` error: expected expression before ‘{’ token rval.adj_list[0] = { {"B","C",3},{"B","A",2} }; ``` Is there a compact way to initialize a dynamically allocated "double array" of pointers to pointers? ``` 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"; } ```