开发者

Square bracket arrays [duplicate]

开发者 https://www.devze.com 2023-02-22 18:44 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Is array name a pointer in C?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Is array name a pointer in C?

So, I usually declare arrays using pointers.

However, you can also declare arrays using square brackets notation:

char a[] = "ok" ;
char b[] = "to" ;
char *pa = a ;

cout << "a " << sizeof( a ) << endl ;   // 3
cout << "pa " << sizeof( pa ) << endl ; // 4

The peculiar thing is, sizeof( a ) will be the actual size of the array in bytes, and not the size of a pointer.

I find this odd, because where is开发者_高级运维 the pointer then? Is a square bracket-declared array actually a kind of datastructure with (sizeof(char)*numElements) bytes?

Also, you cannot re-assign a to b:

a = b ; // ILLEGAL.

Why is that? It seems as though a is the array and not a pointer to the array ("left operand must be l-value" is the error for a = b above). Is that right?


Why is that? It seems as though a is the array and not a pointer to the array ("left operand must be l-value" is the error for a = b above).

a is indeed an array type and not a pointer type. You cannot assign to an array because it is a non-modifiable lvalue.

BTW Array decays to pointer to the first element when it is passed to a function.


When you use the square brackets in your declaration, you are actually allocating space on the stack. When you use the * to declare a pointer, you are simply declaring a pointer. So

char a[] = "ok";

will actually allocate 3 bytes on the stack, and fill it with the string ok\0. However if you do

char a* = "ok";

it will allocate enough room for a pointer, and set the pointer to a location in the data section containing the string ok\0 (i.e. it's compiled in as a constant).


Correct, the type of a is char array of length 3. Array variables can be assigned to pointer variables because array types can decay into a pointer to the first element in the array.


In short, it's a constant pointer to the first (zeroth) element in the array.

Check out the "Pointers and Arrays" section here

0

精彩评论

暂无评论...
验证码 换一张
取 消