C中的静态数组初始化
请考虑以下陈述
typedef struct { int member1; int member2; }Custom_t; void ISR(void) { static Custom_t struct1[SOME_CONSTANT]; ...... ...... }
如何在C编程中将所有member2变量初始化为单个值?
如果我像下面所示的那样使用结构,那么有可能有人在头文件中更改“SOME_CONSTANT”而忘记更新列表。
另一种解决方案是为结构提供当前文件的全局范围。 但是使用该结构的唯一function是ISR()。
void ISR(void) { static Custom_t struct1[SOME_CONSTANT] = { {0, 3}, {0, 3}, ...... ...... }; ...... ...... }
在C中有没有解决这个问题的方法?
如何在.c文件中添加对SOME_CONSTANT
进行硬编码的编译时间检查(例如,在初始化程序之前)?
#if SOME_CONSTANT != #error "SOME_CONSTANT is not equal to " #endif
这个“硬代码”的合理性是每当更改SOME_CONSTANT
,更新初始化程序以及编译时间检查时。
您不需要提前指定数组大小,以后可以计算它:
static Custom_t struct1[] = { {0, 3}, {0, 3}, {13,3}, }; #define SOME_CONSTANT (sizeof struct1 /sizeof struct1[0])
或:使用__LINE__
计算元素数量。
对于具有可配置数量的传感器的项目,我不得不做这样的事情:
[custom_t.h]
typedef struct { int member1; int member2; }Custom_t; #define MAX_CUSTOM_T 4 Custom_t *new_Custom_t (int member1, int member2);
[custom_t.c]
#include "custom_t.h" static Custom_t g_Customt[MAX_CUSTOM_T]; static uint8 g_numCustom_t = 0; Custom_t *new_Custom_t (int member1, int member2) { if ( g_numCustom_t < MAX_CUSTOM_T ) { Custom_t *new_obj = &g_Customt[g_numCustom_t++]; new_obj->member1 = member1; new_obj->member1 = member2; return new_obj; } else { // throw exception? // or go into while(1)? // or software breakpoint if debug? // or just... return NULL; } }
[main.c中]
#include "custom_t.h" Custom_t *myCustom1; Custom_t *myCustom2; Custom_t *myCustom3; somefunc() { myCustom1 = new_Custom_t (0,3); myCustom2 = new_Custom_t (1,3); myCustom3 = new_Custom_t (2,3); // do stuff }
这意味着如果你想创建一个新的,你可能需要或不需要根据它的大小更新MAX_CUSTOM_T,但只需要添加一个新的行调用new_Custom_t(int,int)。 但缺点是它可能需要稍微复杂一些,如果您想要添加更多成员进行初始化,则需要更新传递给new_函数的参数以适应。 这可以通过为参数发送单个单独的结构而不是多个参数(有点像MPLAB和谐)来完成。
您可以使用指定的初始化程序并以这种方式执行此操作:
#include #define SOME_CONSTANT 30 typedef struct { int member1; int member2; } Custom_t; int main(void) { static Custom_t struct1[SOME_CONSTANT] = { [0 ... SOME_CONSTANT - 1].member2 = 30 }; printf("%d\n", struct1[25].member2); printf("%d\n", struct1[19].member2); printf("%d\n", struct1[0].member2); return 0; }