Differance in arrays

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

Differance in arrays

Post by Shane » Sun Jul 19, 2009 10:05 pm

hi,

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

Regards,

Shane
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Differance in arrays

Post by Neo » Tue Jul 21, 2009 3:20 pm

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?
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

Re: Differance in arrays

Post by Shane » Fri Jul 31, 2009 3:45 pm

Thanks. Got it.
Post Reply

Return to “C/C++ Programming”