0

What is the difference between calling Input function for m1, m2 variable of structure. Also what is the use of malloc in struct

struct marks{ int n; int *arr; }; Input(struct marks *s) { Body..... } main() { marks *m1=malloc(sizeof(marks)); marks *m2; Input(m1) ; Input(&m2) ; return 0; }

10th Jan 2021, 8:11 AM
Kamalesh Sekhar Bharadwaj
4 Respostas
+ 1
Thanks for clarifying my doubt
11th Jan 2021, 1:06 PM
Kamalesh Sekhar Bharadwaj
0
I was asking regarding C language only not C++
10th Jan 2021, 1:09 PM
Kamalesh Sekhar Bharadwaj
0
Okay I understand. One more think can you please say me what's the difference between this two line of code marks *m1= malloc(sizeof(marks)); And marks *m1; Which one when to use.
10th Jan 2021, 6:35 PM
Kamalesh Sekhar Bharadwaj
0
Martin Taylor "In C the correct syntax is struct marks *m1 = (struct marks*) malloc(sizeof(struct marks));" Syntactically correct, idiomatic C-style C++ - but quite distasteful in pure C. In C, the idiomatic way is to never cast the return type of malloc(), calloc() or realloc() where void * is automatically type-promoted. If you later change the variable type, you have to trace through the source just to change the pointless cast. On a C89 compiler (still used for portability reasons) where stdlib.h may have been forgotten, the cast may hide compiler warnings for what's clearly a bug. struct marks *m1 = malloc(sizeof(*m1)); is the idiomatic way (in C) and clearly much better since it's type-agnostic. Now 'm1' could be anything from struct, char, or a float pointer and you don't have to touch the allocation code again. - Just a nitpick.
12th Jan 2021, 10:14 PM
Mike A
Mike A - avatar