Pointers and arrays are virtually the same thing.
quote:
dosomthing(&array[0]);
This is correct, although it''s not the nicest way to do it.
Other ways include
dosomthing(array+0);
or just plain
dosomthing(array);
.
If you haven''t done addition or subtraction on a pointer, what happens is that it creates a new pointer of the same type offset by that many bytes times the size of whatever the pointer is of.
Why the heck is that useful? Well, you can do silly things like this:
#include <iostream>void printstring(const char *string) { while(*string != NULL) // while we aren''t pointing to a null character. { cout << *string; // print the character ++string; // and move the pointer to the next character. } }int main(void) { printstring("Hello World"); return 0; }
You can also use a pointer as an array with only one element, like this:
#include <iostream>int main(void) { int * number = new int; // create a pointer to a number number[0] = 5; // set element 0 to 5. cout << number[0] << endl; // display element 0. delete number; // delete the pointer return 0; }
Alas, pointers and arrays are not 100% the same. (They were in C, but the introduction of classes and destructors screwed us.)
int main(void) { int * pointer = new int; // create a pointer int * array = new int[1]; // create an array delete pointer; delete [] array; return 0; }
We have to do something special with the array because otherwise only the destructor for the first object in the array gets called. How does delete know how many elements are in the array? It depends on the compiler, but one common way is this:
New allocates the memory needed, plus a few bytes. The first few bytes are used to store the number of elements in the array, it calls the constructors for all the objects, and returns a pointer a few bytes ahead of the memory it allocated.
When you delete an array, delete will look behind the address you have it to find out how many elements it needs to destroy, calls their destructor, and then frees the memory.
You didn''t really need to know that, but I wanted you to know why it''s important to use the right one, because the compiler will probably let you do both.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.