指针所指内容以数组形式取出是c99新特性?如cp[-1]这样的写法
这样用指针效率会不会降低?
会被编译器优化为*(cp + 1)吗?
[解决办法]
以前的也可以啊
[解决办法]
一直可以的。而且两者效率上也没什么实际差别。
将函数参数声明为数组时,实际上用的就是指针。
[解决办法]
也可以这样认为:数组名这所以可以用“[]”运算符,就是因为数组名表示的也是一个地址。
指针存储的也是地址嘛。
[解决办法]
指针用作cp[1]这种用法是从来就可以的,而且cp[1]总是等价于*(cp + 1),更进一步,甚至还等价于1[cp]。:)
试试下面的代码(仅用于理解数组机制用,不要在任何实际的程序中用它):
#include <stdio.h>
int main()
{
int a[] = {0, 1, 2, 3};
printf( "%d\n ", 1[a]);
return 0;
}
[解决办法]
char sz[10];
1[sz]和sz[1];是同样的内容的
效率来讲是一样的
[解决办法]
《K & R》5.3节:
Rather more surprising, at first sight, is the fact that a reference to a[i] can also be written as *(a+i). In evaluating a[i], C converts it to *(a+i) immediately; the two forms are equivalent. Applying the operator & to both parts of this equivalence, it follows that &a[i] and a+i are also identical: a+i is the address of the i-th element beyond a. As the other side of this coin, if pa is a pointer, expressions might use it with a subscript; pa[i] is identical to *(pa+i). In short, an array-and-index expression is equivalent to one written as a pointer and offset.
There is one difference between an array name and a pointer that must be kept in mind. A pointer is a variable, so pa=a and pa++ are legal. But an array name is not a variable; constructions like a=pa and a++ are illegal.
When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address. We can use this fact to write another version of strlen, which computes the length of a string.
节选的这几段话介绍了数组和指针的部分关系。如果要更详细的了解,建议还是把这章细读一遍。
[解决办法]
呵呵,就是个指针跟整数的加法嘛,谁加谁不一样呢。
不过C/C++允许这样,其实我也不太看好。
[解决办法]
cp[-1] 应该算很正常的写法 ...
-1[cp] 这样写应该是讨好些汇编程序员, 他们很喜欢把偏移写前面, 基址写后面 ...
[解决办法]
-1[cp] 帅一点
[解决办法]
没听说有什么效率问题。