I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials here. I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
If you want to be able to alter the size of your array at run time, then declare dynamic arrays. These are done with pointers and the new operator. For the basics on pointers, read the pointers section.
Allocate memory using new, and then you access the array in the same way you would a static array. For example,
int* arrayPtr = new int[10]; for (int i = 0; i < 10; i++) { arrayPtr[i] = i; }
The memory picture is identical to the static array, but you can change the size if you need to. Don't forget you must deallocate the memory before allocating new memory (or you will have a memory leak).
delete [] arrayPtr; // the [] is needed when deleting array pointers arrayPtr = new int[50]; . . .
When you're completely done with the array, you must delete its memory:
delete [] arrayPtr;
Dynamic multi-dimensional arrays are done in a similar manner to Java. You will have pointers to pointers. For an example, see a
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between int *pointerArray = new int[10]; and int array[10]; if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
Output:
5
5
5
5
0x8f94030
0xbfa6a37c
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
T*,+ 5means+ 5 * sizeof(T).std::vector<int>if you can, much much easier.delete[] pointerArray.vectorclass for dynamic arrays. There is a school of thought which believes that the goal when teaching C++ is to maximize the number of bugs the students can make afterwards, by teaching them only the worst way to do everything. Since the material you found follows this philosophy, the best you can do if you want to learn C++ is run away screaming. Then buy a book on C++std::vectoris available, still they talk about creating dynamic arrays usingnew[].