is it better to have an array on the stack or the heap? and why are the reasons for whatever answer you may give. thanks a lot :)
Printable View
is it better to have an array on the stack or the heap? and why are the reasons for whatever answer you may give. thanks a lot :)
It depends what you want to do, however if efficiency is a concern it's better to declare them on the stack if possible .
If you know the size of the array at compile time use the stack
If the array size is unknown (i.e. if it depends upon the user's input) then you should use just the amount you need from the heap instead of declaring a huge array on the stack.
i was under the impression that an array had to have a fixed size at compile time. could you give me an example of how to allow an array size to be user defined, as
type ArrayName[x] doesn't work.
thanks a lot.
int num;
cout << "how big an array do you want?" << endl;
cin >> num;
int *array = new array[num];
cout << "you got it buddy." << endl;
cout << "now to get rid of the memory after you are done I need to do a bit of behind the scenes magic." << endl;
delete [] array;
array is an array of size num that is declared on heap using user input and after being used for the last time (never here) delteted to prevent memory leaks.
Unregistered said:
I'm sure he meant to say:Quote:
int *array = new array[num];
array then is essentially an array of num integers.Code:int *array = new int[num];
boy am I screwing up today. Maybe I should just take a back seat and watch until I can get a few more zzzzzzzzzzzzzzzz's.