Page 1 of 1

Differance in arrays

Posted: Sun Jul 19, 2009 10:05 pm
by Shane
hi,

I have a question in C++ arrays.
Is it equal to define int myArray[256] and int *myArray = new int[256]; ?

Regards,

Shane

Re: Differance in arrays

Posted: Tue Jul 21, 2009 3:20 pm
by Neo
There two ways to define arrays in C++. Static and dynamic definitions.

Code: Select all

int myArray[256];                 // Static definition
int *myArray = new int[256]; // Dynamic definition
When accessing the arrays there is no difference. However Static arrays are created at function load-time and the size of the array is fixed.

Dynamic arrays are created at run-time and the size can be adjusted as required anywhere in the code.

There is one important thing about dynamic arrays. Whenever you don't need the dynamic array anymore, it is required to remove it from memory by using 'delete' statement to avoid memory leaks.

Code: Select all

int size = 256;
int *myArray = NULL;       // new pointer declared
myArray = new int [size]; // memory dynamically allocated
 
/* .......
Your code here
........*/
 
delete [] myArray;           // memory freed up
myArray = NULL;             // pointer changed to NULL
To avoid unnecessary problems, try to use statically defined arrays as much as possible. Only use dynamic array when it is really required.

Does that make sense?

Re: Differance in arrays

Posted: Fri Jul 31, 2009 3:45 pm
by Shane
Thanks. Got it.