方括号数组
可能的重复:
数组名称是 C 中的指针吗?
所以,我通常声明数组使用指针。
但是,您也可以使用方括号表示法声明数组:
char a[] = "ok" ;
char b[] = "to" ;
char *pa = a ;
cout << "a " << sizeof( a ) << endl ; // 3
cout << "pa " << sizeof( pa ) << endl ; // 4
奇怪的是,sizeof( a )
将是数组的实际大小(以字节为单位),而不是指针的大小< /em>.
我觉得这很奇怪,因为指针在哪里?方括号声明的数组实际上是一种具有 (sizeof(char)*numElements)
字节的数据结构吗?
另外,你不能将 a 重新分配给 b:
a = b ; // ILLEGAL.
为什么呢?看起来好像 a 是数组,而不是指向数组的指针(“左操作数必须是左值” 是 a = b< 的错误/代码> 上面)。是这样吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
a
确实是数组类型而不是指针类型。您无法分配给数组,因为它是不可修改左值。
BTW 数组在传递给函数时会衰减为指向第一个元素的指针。
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.
当您在声明中使用方括号时,实际上是在堆栈上分配空间。当您使用
*
声明指针时,您只是声明了一个指针。因此char a[] = "ok";
实际上会在堆栈上分配 3 个字节,并用字符串 ok\0 填充它。但是,如果您执行
char a* = "ok";
,它将为指针分配足够的空间,并将指针设置到数据部分中包含字符串
ok\0
的位置code> (即它被编译为常量)。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. Sochar a[] = "ok";
will actually allocate 3 bytes on the stack, and fill it with the string
ok\0
. However if you dochar 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).正确,
a
的类型是长度为 3 的 char 数组。数组变量可以分配给指针变量,因为数组类型可以衰减为指向数组中第一个元素的指针。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