简体   繁体   English

char *和char []

[英]char * and char[]

Why is this right ? 为什么这是对的?

#include<iostream>
using namespace std;
int main()
{
    char *s="raman";
    char *t="rawan";
    s=t;
    cout<<s;

return 0;
}

But this is wrong? 但这是错的?

#include<iostream>
using namespace std;
int main()
{
    char s[]="raman";
    char t[]="rawan";
    s=t;
    cout<<s;

return 0;
}

In the first example, s=t does a pointer assignment. 在第一个例子中, s=t进行指针赋值。 In the second, s=t tries to assign a pointer value (resulting from the implicit conversion, or "decay", of the array expression t ) to an array object. 在第二个中, s=t尝试将指针值(由数组表达式t的隐式转换或“衰减”产生)分配给数组对象。 C++ doesn't permit array assignments. C ++不允许数组赋值。

C and C++ happen to be very similar in this area; C和C ++在这个领域恰好相似; section 6 of the comp.lang.c FAQ covers the relationship between arrays and pointers very well. comp.lang.c FAQ的第6节很好地介绍了数组和指针之间的关系。

The first example assigns an pointer to another which is valid. 第一个示例将指针指向另一个有效的指针。

The second example assigns an array to another array which in not allowed in C & C++ both. 第二个例子将一个数组分配给另一个数组,这个数组在C&C ++中都不允许。


This excellent C++ FAQ entry and this answer should be a good read for you. 这个优秀的C ++ FAQ条目和这个答案应该是一个很好的阅读。

In addition to what the other guys said: 除了其他人说的话:

Contrary to popular belief, arrays are actually not pointers. 与流行的看法相反,数组实际上不是指针。 They just share a lot of similarities when working with them and have a couple of implicit conversions to pointers which is why it's easy to work with them as if they are pointers. 他们在使用它们时只是分享了许多相似之处,并且对指针进行了几次隐式转换,这就是为什么它们很容易使用它们就好像它们是指针一样。

Arrays are a standalone feature of (C and) C++. 数组是(C和C ++)的独立功能。 It doesn't behave exactly like a pointer would. 它的行为与指针不完全相同。

For example, it's possible to allocate array objects on the stack, which is not possible when you allocate objects using new (which returns a pointer) and pointers. 例如,可以在堆栈上分配数组对象,这在使用new(返回指针)和指针分配对象时是不可能的。

And the example that you showed is another one: You can't use arrays as if they are pointers. 您展示的示例是另一个示例:您不能将数组用作指针。 But you can use pointers to point to a continuous piece of memory (array). 但是你可以使用指针指向连续的内存(数组)。

char *s means: char *s表示:
address and value both are not constant. 地址和价值都不是一成不变的。

const char *s:

value is constant, not address. 值是常数,而不是地址。

const char * const s;

address and value both are constant. 地址和价值都是不变的。

char *s[] 

is an array. 是一个数组。 Array base address is always contant. 数组基址始终存在。 You can not change the base address of it, that is not allowed in c. 您无法更改它的基址,这在c中是不允许的。

Array name is a const pointer. 数组名称是一个const指针。 meaning, when you declare an array, the name is a pointer, which cannot be altered. 意思是,当你声明一个数组时,名称是一个指针,不能改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM