Question

I am just starting to learn C and am having a tough time trying to initialize an array of structs. Basically, the high level goal is to take a string, like a mustache template, and break it apart into either "static string" or "variable" tokens, which are stored in an array. Then theoretically, to render the array, you would check "if it's a string, just copy the string, otherwise if it's a variable, get the value and add it to the string".

So one of the first steps is to just initialize an array that can handle an arbitrary number of tokens, here's what I have been trying:

typedef struct {
  int *type; // probably pointing to an enum or something, but not there yet
  char *value;
} token;

typedef struct {
  // token *tokens[] // how to do this?
} template;

template
compile(char *source) { // source string
  token tokens[] = malloc(sizeof(token) * 20) // 20 is arbitrary max
  // ... rest of code
}

So there's 2 places with token tokens[]. How should this be written? I keep getting this error no matter if I try references or no reference:

error: array initializer must be an initializer list
  token tokens[] = malloc(sizeof(tokens));

Just to note, I see in C++ there is the vector class, but I just want to do this in straight C.

Was it helpful?

Solution

You can do

typedef struct {
  token* tokens;
} template;

t.tokens = malloc(sizeof(token)*20);

token* tokens[20] will give you an array of 20 pointers to tokens. This would useful when you want 20 lists of tokens. But from your question I assume, that you only want one list ok tokens, so just use token* tokens.

An alternative is:

typedef struct {
  token tokens[20]; // now you don't need malloc at all!
} template;

In the first approach, the number of tokens can be dynamic and given at runtime. For the second version, the (maximum) number of tokens must be known at compile time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top