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);
}
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
ptrdate
gets changed in futuretypedef
ed 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With