See sometimes I have
typedef struct _student
{
// some data
} STUDENT;
NOW
main()
{
int noOfStudent;
STUDENT *b;
//some work
noOfstudent = this_much_student();
STUDENT a[noOfStudent]; // way 1
b=(STUDENT*)malloc(sizeof(STUDENT)*noOfStudent); // way 2
}
Somewhere I read that all variables should be defined at the beginning of a function and the defination of variables in the middle of function should be ignored, So in such condition
does way1 is good ? or way2 is good ? and why?(Justify)
Edit :
i am coding to target c89 compiler and i want the scope is limited to this function only
The first way:
defines a variable-length array. This is a C99-only feature.* The array lives on the stack, and is automatically cleared up once it goes out of scope (e.g. when the function ends). One disadvantage is that if you need a very big array, you will probably cause a stack overflow.
The second way:
should probably be rewritten as:
Either way, it dynamically creates memory on the heap. This avoids the potential for stack overflow, but it does require you to explicitly
free()the memory when you’re finished with it.* However, many C or C++ compilers will offer it as a non-standard extension.