我有以下代码
serial.flushInput()
serial.readline() #do not save this value - throw away
while (serial.inWaiting()==0): #wait until there is data
pass
valueRead = serial.readline() #keep this value
现在我要分配堆内存
这是我的尝试
struct USER{
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} *administrator;
不确定这是否正确...
答案 0 :(得分:7)
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} *administrator;
这不仅是一个结构声明,它还是一个变量声明...它与:
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
};
struct USER *administrator;
因此,当您随后使用sizeof(administrator)
时,将得到“ 指针的大小” ...这很可能不是想要。
您可能想做更多类似的事情:
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
};
int main(void) {
struct USER *administrator;
administrator = malloc(sizeof(*administrator));
/* - or - */
administrator = malloc(sizeof(struct USER));
/* check that some memory was actually allocated */
if (administrator == NULL) {
fprintf(stderr, "Error: malloc() returned NULL...\n");
return 1;
}
/* ... */
/* don't forget to free! */
free(administrator)
return 0;
}
sizeof(*administrator)
和sizeof(struct USER)
都将为您提供“ USER结构的大小”,因此malloc()
的结果将是指向足够的内存来存储结构的数据。
答案 1 :(得分:0)
struct USER{
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} *administrator;
这将管理员定义为指针变量。但是,从其他代码开始
administrator *newStruct = (administor*)malloc(sizeof(administrator));
您似乎想将其用作类型。 为此,您可以使用typedef。
typedef struct USER{
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} administrator;
然后使用
administrator *newStruct = (administrator *)malloc(sizeof(administrator));