我没有找到这个问题的确切答案,所以要么这是一个愚蠢的问题,要么是显而易见的。我想知道它是否会产生未定义的行为。
我定义了一些结构类型:
typedef struct {
char string1[17];
char string2[33];
int someInt;
float someFloat;
} my_struct_t;
我需要该结构的多个实例(就像你在结构数组中一样),但对象的数量在编译时是未知的。
像这样初始化它是否正确?
my_struct_t *myStruct;
size_t noOfElements;
size_t completeSize;
int index;
/* ...code which sets the number of elements at runtime... */
completeSize = sizeof(my_struct_t) * noOfElements;
myStruct = malloc(completeSize);
memset(myStruct, 0, completeSize);
/* ...and then access it as if it were an array...*/
myStruct[index].someInt = 10; // index < noOfElements
这样做安全吗?这memset()
部分是我担心的。