Whats the difference between these 2 and why should I use one over the other?
1 2 3 4 5 6 7
int i;
cout << "how many dogs?" << endl;
cin >> i;
int dogs[i];
1 2 3 4 5 6 7
int i;
cout << "how many?" << endl;
cin >> i;
int *dogs= newint[i];
delete [] dogs;
Both of these seem to achieve the same thing.
can someone explain how this works exactly?
int *dogs= newint[i];
why is it necessary to have a pointer to dogs?
I get that it has something to do with run time but can someone provide an example of where we don't use new which wouldn't work because of a run time error?
The first one is incorrect, as in it's illegal in C++. Some compilers allow line 5 to work as a language extension, but the standard only permits array sizes to be constant. Line 7 is erroneous, as arrays declared this way are stored on the stack. You don't need to manually free memory allocated on the stack.
The second is correct and legal, and the array is stored on the heap. Line 5's newint[i] allocates a block of memory on the heap that's enough for i integers, and returns a pointer to the start of that memory, which is stored in dogs. The only way to access that memory is by dereferencing a pointer to it. Should you lose that pointer, you lose that memory, and for that matter, so does the OS until your program terminates.
Generally, new is used when the amount of memory required isn't known at compile-time for any reason, or when you need to allocate a massive amount of memory (the stack, compared to the heap, is quite small).
Smart pointers are a way for programmers to admit that they are undisciplined and cannot keep track of their own memory to reduce the chance of a memory leak happening, namely when a pointer to memory on the heap gets lost.
With the number of things in C++ that can suddenly cause a pointer to memory to be lost (namely exceptions causing local variables to go out of scope), it's a very good habit to use smart pointers.