c++ use of ptr as array base
On page 42 of Effective C++, a pointer is used as an array name ala
AirPlane *new开发者_运维百科Block = ...
newBlock[i].next=0;
I've not been aware that this is legal. Is this part of the c++ standard? Is it common practice?
Yes, pointers can be used to dynamically allocate arrays of objects.
From this and other questions it appears that you're a newbie with C++. Therefore, starting with "Effective C++" isn't the best idea. While it's a great book, it's most useful for people already familiar with the language. You should start with an introductory book or tutorial, work through it, write some code and only then turn to "Effective C++".
From http://www.cplusplus.com/doc/tutorial/pointers/:
In the chapter about arrays we used brackets ([]) several times in order to specify the index of an element of the array to which we wanted to refer. Well, these bracket sign operators [] are also a dereference operator known as offset operator. They dereference the variable they follow just as * does, but they also add the number between brackets to the address being dereferenced. For example:
a[5] = 0; // a [offset of 5] = 0
*(a+5) = 0; // pointed by (a+5) = 0
These two expressions are equivalent and valid both if a is a pointer or if a is an array.
I would repeat answer I've given to similar question C strings confusion:
It is confusing indeed. The important thing to understand and distinguish is that char name[] declares array and char* name declares pointer. The two are different animals.
However, array in C can be implicitly converted to pointer to its first element. This gives you ability to perform pointer arithmetic and iterate through array elements (it does not matter elements of what type, char or not). As @which mentioned, you can use both, indexing operator or pointer arithmetic to access array elements. In fact, indexing operator is just a syntactic sugar (another representation of the same expression) for pointer arithmetic.
The very same rules are specified in C++ standard.
Also, take a look at Is array name a pointer in C?
精彩评论