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; }
4 Respuestas
+ 1
Thanks for clarifying my doubt
0
I was asking regarding C language only not C++
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.
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.