I'm a bit confused about allocating memory for my variables. If e.g. I'm creating a large data structure (an array, a struct, an object, etc.), and I'm initializing it in main()'s scope, should I crea开发者_开发技巧te a local variable
int chessBoard[8][8] = ...
or should I allocate memory on the heap?
int * chessBoard = new array[8][8];
*chessBoard = ...
Does it matter? Is it preferential? Is one more efficient/smarter? I personally like allocating memory for larger objects I don't feel are small enough for a stack frame. But I really don't know.
The major reason to use dynamic memory allocated by malloc is when you don't know the maximum amount of memory you need at compile time. For a chessboard, the size is always eight by eight, and an array is fine. On most computers an eight by eight int array is tiny.
For lists of names, you rarely know the maximum number you might encounter, so use malloc.
Arrays are a little faster because the compiler reserves the space. With malloc, there is a run-time call to a library function to request the memory. Once you have the memory, either way is generally the same speed.
Using pointers to access the memory allocated by malloc is a little more complicated than simply using an array. But you should understand both if you are going to be a C programmer.
For very large amounts of memory, you have to use malloc.
The biggest mistake made with memory allocated by malloc is forgetting to free it when you are done with it. If you forget to free it, you can have a memory leak.
It's generally better to allocated memory using malloc when the object ownership needs to be passed around a lot. If the object is going to be used in the single reference block and won't fall out of scope, then a local variable is definitely better. It all comes down to "do you need to hang onto it after the loop is done".
If it's defined in main() as you hint, then it'll certainly be valid forever (till app close), in which case it becomes much more a matter of personal preference. Many people prefer local variables because they're easier to read and the dereferencing doesn't look as messy.
You should consider size of objects you allocate, becouse code like this:
int something[10000000];
will cause memory error, but:
int *something = new int[10000000];
will work fine.
精彩评论