Skip to content

Instantly share code, notes, and snippets.

@svenoaks
Last active January 3, 2016 15:59
Show Gist options
  • Save svenoaks/8486273 to your computer and use it in GitHub Desktop.
Save svenoaks/8486273 to your computer and use it in GitHub Desktop.
int length = 100; //value of length can be determined at run-time
int *dyn = new int[length]; //new int[length] returns a pointer to
//first element of the array.
cout << "Using pointers:" << endl;
*dyn = 10; //dyn[0] and *dyn are equivalent!
*(dyn + 1) = 15; // *(dyn + 1) and dyn[1] are equivalent!
cout << "dyn[0] = " << dyn[0] << endl;
cout << "dyn[1] = " << dyn[1] << endl;
cout << endl;
cout << "Using array index:" << endl;
dyn[0] = 20;
dyn[1] = 25;
cout << "dyn[0] = " << dyn[0] << endl;
cout << "dyn[1] = " << dyn[1] << endl;
delete[] dyn; //the memory must be deallocated.
dyn = NULL; //trying to use the pointer again
//would result in undefined
Output is:
dyn[0] = 10
dyn[1] = 15
dyn[0] = 20
dyn[1] = 25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment