使用指向其结构或结构本身的指针分配内存更好吗?

Is it better to allocate memory using a pointer to its struct, or the struct itself?

通过将实际代码中标有 (1) 的行替换为:

,我得到了相同的值
Date *ptrdate = malloc(12 * sizeof(*ptrdate));

问题:哪个更好,为什么?

这是我的实际代码:

typedef struct {
    int day;
    int mo;
} Date;

void main(){
    Date *ptrdate = malloc(12 * sizeof(Date)); //(1)

    ptrdate[0].day=26;
    ptrdate[0].mo=5;
    printf("Date:%d/%d\n", ptrdate[0].day, ptrdate[0].mo);
}

将您的代码编写为

Date *ptrdate = malloc(12 * sizeof(*ptrdate));

或者,更简洁的方法

Date *ptrdate = malloc(12 * sizeof *ptrdate);  //sizeof is operator, no need for extra "()"

更容易接受和更受欢迎,因为它使代码更健壮。即使

  • ptrdate 的类型将来会改变
  • 将代码与任何具有单独typedefed Date 的外部库一起使用(造成冲突)[#]

您不需要更改这部分代码。

另外,main()推荐的签名是int main(void)


[#]感谢 @Elias Van Ootegem 先生在下方发表评论]

这更多的是taste/style的事情。我更喜欢 sizeof(Date) 因为这对我来说似乎更易读。但随心所欲-这里没有真正的区别。