Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

malloc

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

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);
}
like image 279
LED Fantom Avatar asked Feb 10 '23 08:02

LED Fantom


1 Answers

Writing your code as

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 code more robust. Even if

  • the type of ptrdate gets changed in future
  • using the code along with any external library which has a seperatetypedefed Date (creating a conflict)[#]

you don't need to change this part(s) of code.

Also, the recommended signature of main() is int main(void).


[#]Thanks to Mr. @Elias Van Ootegem for the comment below]

like image 128
Sourav Ghosh Avatar answered Feb 13 '23 04:02

Sourav Ghosh