[英]How can I pre define an array of structs
我的c非常好用,我什至都不100%如何問這個問題,所以請多多包涵。
基本上,我試圖做的是創建一個筆記結構的查找表。
我知道我想要的結構,並且擁有要放入其中的所有數據。
那么我該如何:
A)創建一個notes_type_t數組,並用我所有的數據填充它。
- - 要么 - -
B)用所有數據定義一個宏
- - 要么 - -
C)更好的方法
typedef struct
{
float freq;
int midi;
char[2] note;
}notes_type_t
{
16.4, 12, C
17.3, 13, C#
18.4, 14, D
19.4, 15, D#
20.6, 16, E
21.8, 17, F
23.1, 18, F#
24.5, 19, G
26, 20, G#
27.5, 21, A
29.1, 22, A#
30.9, 23, B
32.7, 24, C
34.6, 25, C#
36.7, 26, D
38.9, 27, D#
41.2, 28, E
43.7, 29, F
46.2, 30, F#
49, 31, G
51.9, 32, G#
}
可能類似於以下內容。 假設它在notes.h
:
typedef struct
{
float freq;
int midi;
char note[3];
}notes_type_t;
#if defined( DEFINE_NOTES )
notes_type_t notes[] = {
{16.4, 12, "C"},
{17.3, 13, "D#"},
...
};
#else
extern notes_type_t notes[];
#endif
然后,在一個源文件中,如圖所示包含具有#define
notes.h以實際定義數組。 其他源文件將僅具有#include
並獲取數組的extern
聲明。
#define DEFINE_NOTES
#include "notes.h"
請注意, note
元素必須為3個字符(以便為空終止符留出空間)。
notes_type_t arr[] = {
{16.4, 12, "C"},
{17.3, 13, "C#"},
{18.4, 14, "D"},
{19.4, 15, "D#"},
{20.6, 16, "E"},
{21.8, 17, "F"},
{23.1, 18, "F#"},
{24.5, 19, "G"},
{26, 20, "G#"},
{27.5, 21, "A"},
{29.1, 22, "A#"},
{30.9, 23, "B"},
{32.7, 24, "C"},
{34.6, 25, "C#"},
{36.7, 26, "D"},
{38.9, 27, "D#"},
{41.2, 28, "E"},
{43.7, 29, "F"},
{46.2, 30, "F#"},
{49, 31, "G"},
{51.9, 32, "G#"},
};
請注意您的note
字段太小。 AC字符始終以\\0
終止,因此總是比您看到的大一個。 同樣,您的note
字段似乎應該具有可變的長度,因此您可能想使用const char*
代替。
還值得考慮的是大數據字段(您的示例不算大)對可執行文件大小等的影響。我寧願從文件中讀取此信息,這是程序一旦開發就必須執行的操作無論如何。
您的代碼有很多錯誤。 這是一些可編譯並打印“ C”和“ C#”的工作代碼。
typedef struct note
{
float freq;
int midi;
char name[3];
} note;
note notes[] =
{
{16.4, 12, "C"},
{18.4, 14, "C#"},
/** you can fill in the rest of the notes here **/
};
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%s\n", notes[0].name);
printf("%s\n", notes[1].name);
return 0;
}
為了避免混淆,我將char數組從“ note”更改為“ name”。 我也認為您需要3個字符才能容納空終止符,盡管我不確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.