The differences between array and pointer
In fact, the name of array and pointer are totally different stuff.
The name of array represents a certain kind of data structure of array.
For example, when you declare an array with "char amessage[]= "now is the time" ". Then declare a pointer with "char *pmessage="now is the time"".
Then array amessage is built as a data structure which contains the whole copy of string "now is the time". However pointer pmessage just contains the address of the string literal.
So the size of amessage is 16, however the size of pmessage is only 4.
But why sometimes the name of array can be used as pointer?
This is because of the compiler. When the compiler finds that the name of array appears in the right of a statement without index, the compiler will make it act as pointer - something like &amessage.
But whatever the name of array is not pointer after all, so it cannot appear in the left of statement.
Compile the following code, you can also get the conclusion we talked above.
#include <string.h>
#include <iostream.h>
int main (int argc, char* argv[])
{
char str[10];
char *pStr = str;
cout << sizeof(str) <<endl;
cout << sizeof(pStr) <<endl;
return 0;
}
However, when the name of array appears as formal parameter in subfunctions, it becomes a pointer, because we are not supposed to declare a large formal parameter, or a parameter which is fixed with some value. So from these points, pointer is the best choice.
Summary:
- The name of array is not pointer, it is just a data structure.
- The name of array cannot appear in the left of statement.
- When the the name of array appears as formal parameter in subfunctions, it becomes pointer.
References:
[2] 在C语言中"指针和数组等价"到底是什么意思? http://c-faq-chn.sourceforge.net/ccfaq/node78.html
[3] C: differences between pointer and array http://stackoverflow.com/questions/1335786/c-differences-between-pointer-and-array
Comments
Post a Comment