static and dynamic memory allocation

Posted 30 November 2007 - 03:47 AM

Hello,
I want to know if the static and dynamic memory allocation make any difference in the values of the variables. It should not obviously but i preferred to confirm.
say i have a variable x and i know that a max of 1000 values are assigned to x, then does using
int x[1000];
or
int *x=new int[1000];
make any difference to the values?
Thanks,
Prads

Re: static and dynamic memory allocation

Posted 30 November 2007 - 04:12 AM

As far as usage syntax goes you can treat 'x' as an array in both cases (ie, you can use the array subscript operator, [ ] for both). The reasons for picking a statically allocated array versus a dynamically allocated array are down to trade-offs between flexibility and safety. Neither method is perfect, so when it comes down picking between the two, you ought to keep some of these points in mind

static array allocation
- The size of the array must be a constant that the compiler knows at compile time. The array cannot change size at any time.
- The size of the array can be detected with the sizeof operator, or using template parameter deduction.
- The array variable cannot be reassigned to any other array.
- There is no danger of a memory leak

dynamic array allocation
- The size of the array can be any integer.
- The size of the array cannot be picked up automatically. the programmer must devise some way of tracking the size of the array. this is usually by keeping a 'size' variable.
- The array's pointer can be reassigned to any other memory location
- Risk of memory leak if the pointer is reassigned, or goes out of scope

Its worth noting that in C++ there is a better alternative to both the above, which comes in the form of the Standard Template Library's vector type. vector is the "C++ array" which combines the static safety of a statically allocated array, with the flexibility of a dynamically allocated array.