0

这个网站上最接近的问题,我有几个答案让我不满意。

基本上,我有两个相关的问题:

问:如果我这样做:

char a[]= "abcde"; //created a string with 'a' as the array name/pointer to access it.

a[0]='z';  //works and changes the first character to z.

char *a="abcde";
a[0]='z'; //run-time error.

有什么区别?没有“const”声明,所以我应该可以自由更改内容,对吧?

问:如果我这样做:

int i[3];
i[0]=10; i[1]=20; i[2]=30;
cout<<*++i;  //'i' is a pointer to i[0], so I'm incrementing it and want to print 20.

这给了我一个编译时错误,我不明白为什么。

另一方面,这有效:

int *i=new int[3];
i[0]=10; i[1]=20; i[2]=30;
cout<<*++i;  //Prints 20.

谢谢您的帮助。

4

2 回答 2

1

问题 1

问题是它仍然是常量。

字符串文字实际上具有类型char const*
但是当他们设计 C++03 时,他们决定(不幸的是)从char const*to转换char*不是错误。因此代码:

char *a="abcde";

实际上编译没有错误(即使字符串是 const)。但是字符串文字仍然是 const,即使它是通过非 const 指针指向的。从而使其非常危险。

好消息是大多数编译器都会生成警告:

警告:不推荐将字符串常量转换为 'char*'</p>

问题2

cout<<*++i;  //'i' is a pointer to i[0], so I'm incrementing it and want to print 20.

此时 i 不是指针。它的类型仍然是一个数组。
递增数组不是有效的操作。

你在想的事情;是数组在帽子掉落时衰减为指针(例如当您将它们传递给函数时)。不幸的是,在这种情况下并没有发生这种情况,因此您试图增加一个数组(这没有意义)。

于 2013-10-27T21:05:56.960 回答
1

char *a="abcde";
a[0]='z'; //run-time error.

Ans - 这里a指向存储在只读位置的字符串文字。您不能修改字符串文字

int i[3];
i[0]=10; i[1]=20; i[2]=30;
cout<<*++i; 

Ans-数组和指针不是一回事。这里i不是指针。您需要左值作为增量操作数

你可以做 :

int *p = &i[0];
std::cout<<*++p;

在最后一种情况下,运算符new返回一个指向已分配内存空间的指针,因此它是可能的。

于 2013-10-27T21:04:45.293 回答