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

I got the same values ​​by replacing the line labeled (1) in my actual code with the following:

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

Question: Which one is better and why?

Here is my actual code:

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);
}
+4
source share
2 answers

Writing code like

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

or, a cleaner approach

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

is more acceptable and desirable as it makes the code more reliable. Even

  • type ptrdatewill be changed in the future
  • using code along with any external library that has a separate typedefed Date(create conflict) [#]

You do not need to modify this part of the code.

, main() int main(void).


[#] Mr. @Elias Van Ootegem ]

+7

/. sizeof(Date), . , - .

+1

Source: https://habr.com/ru/post/1584239/


All Articles