hi,
I have a question in C++ arrays.
Is it equal to define int myArray[256] and int *myArray = new int[256]; ?
Regards,
Shane
Differance in arrays
Re: Differance in arrays
There two ways to define arrays in C++. Static and dynamic definitions.
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.
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?
Code: Select all
int myArray[256]; // Static definition
int *myArray = new int[256]; // Dynamic definition
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
Does that make sense?
Re: Differance in arrays
Thanks. Got it.