[英]How do you initialize a dynamic array of structs in C?
我剛剛開始學習C,並且在嘗試初始化結構數組時遇到了困難。 基本上,高級目標是將一個字符串(如小胡子模板)分成一個“靜態字符串”或“可變”令牌,將它們分解存儲在數組中。 然后,從理論上講,要渲染數組,您將檢查“如果它是一個字符串,只需復制該字符串,否則,如果它是一個變量,則獲取值並將其添加到字符串中”。
因此,第一步就是初始化一個可以處理任意數量標記的數組,這就是我一直在嘗試的方法:
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
}
所以有2個地方有token tokens[]
。 應該怎么寫? 無論我嘗試引用還是不引用,我都會不斷收到此錯誤:
error: array initializer must be an initializer list
token tokens[] = malloc(sizeof(tokens));
只是要注意,我看到在C ++中有向量類,但是我只想在直接C語言中執行此操作。
你可以做
typedef struct {
token* tokens;
} template;
t.tokens = malloc(sizeof(token)*20);
token* tokens[20]
將為您提供20個指向令牌的指針的數組。 當您需要20個令牌列表時,這將很有用。 但是從您的問題來看,我假設您只想要一個列表ok令牌,因此只需使用token* tokens
。
一種替代方法是:
typedef struct {
token tokens[20]; // now you don't need malloc at all!
} template;
在第一種方法中,令牌的數量可以是動態的,並且可以在運行時指定。 對於第二個版本,必須在編譯時知道(最大)令牌數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.