(6) const int arrsize = 80; //When is this destroyed? |
Numeric constants don't necessarily use any memory at all. This is one such case, because you've only used the constant as a size for arrays.
(10) static int arr_size = 80; //These and the above are same. |
Actually, no, they're not the same.
Since arr_size is never used, I think it's possible the compiler will optimize it away, but if you had used it somewhere, the compiler would have needed to reserve a little bit of memory for it, which would be released when the program terminates.
(11) int a[arrsize]={1,2,3,4,5,6}; //How is this stored? Does it get destroyed as I leave main() ? |
It's stored on the stack, and yes, once main() returns a's memory will be released automatically.
a[arrsize]={1,2,3,4,5,6} <------- Why is this wrong? Separate declaration and initialization |
There's two different conceptual errors here.
First, once an array has been declared,
a[arrsize]
refers to a single element of the array (actually, it erroneously refers to one element past the end of the array, but we'll ignore that for now). Therefore, this:
1 2
|
int a[arrsize];
a[arrsize]={1,2,3,4,5,6};
|
is wrong for the same reason that this is wrong:
1 2
|
int x;
x={1,2,3,4,5,6};
|
Second, arrays cannot ever be assigned directly. This would still be wrong:
1 2
|
int a[6];
a={1,2,3,4,5,6};
|
You can accomplish that by several different methods. For example:
1 2 3
|
int a[arrsize];
static const int data[] = {1,2,3,4,5,6};
std::copy(data, data + 6, a);
|
(19) int* p = new int (100); //I don't need to give the location a variable? Just (*p) is enough? |
I don't understand the question.
(21) delete p; //What if I don't delete here? |
If you never delete, you will leak memory. If you're just dealing with basic types and the program exits immediately, it's
probably not a problem (although it's still bad form).
If you allocate memory in a loop and never delete it, you will eventually exhaust all the memory in the machine.
If you're dealing with non-trivial objects, not releasing them can have unpredictable effects that may or may not remain once your program has terminated.
In short, if you allocate memory you should release it. Better yet, don't use new and delete if you can avoid it, and always use containers and/or smart pointers.