0

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

Rob W
  • 341,306
  • 83
  • 791
  • 678
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222

2 Answers2

2

The first way:

STUDENT a[noOfStudent];

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:

b=(STUDENT*)malloc(sizeof(STUDENT)*noOfStudent);

should probably be rewritten as:

b=malloc(sizeof(*b)*noOfStudent);

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.
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

It depends on whether the compiler allows array of dynamic length. If it does not, then way2 is the only option.

If is does (C99) then the decision can be taken by the scope of the variable.

If the scope of STUDENT object is only inside a function then way1 or way 2 can be a good option. If you use way 2, you may need to explicitly free it.

Otherwise, if you need the scope of the object outside the scope of the function, you have to go with way 2 and allocate the memory in heap.

M S
  • 3,995
  • 3
  • 25
  • 36