你表達(&set + 1)
響應將指向一個過去的數組,如果設置是一個數組,但它不是。變量集合是一個變相指針(不是一個數組),所有數組看起來像是按值傳遞的。這
更好的例子:
void g(int a[3]);
// exactly the same as:
void g(int* a);
// note the 3 is ignored by the compiler here! it serves as documentation when
// reading the code, but nothing else, and for this reason you should pretty much
// always drop it, preferring:
void g(int a[]); /*or*/ void g(int* a); // (which are also identical)
void f() {
int a[3] = {0, 1, 2};
int* end = (int*)(&a + 1); // &a has type int (*)[3] (that's pointer to array
// of 3 ints so &a + 1 has the same value as &a[2] + 1 ("one past" the last
// valid item in a)
int* p = a; // this is how a is passed "by value" to a function such as g
end = (int*)(&p + 1); // even though this "looks" the same, &p has type int**
// and adding 1 to that has no correlation with what p points to.
// to make matters worse, the cast (and C++-style casts have the same problem
// here) hides this type error and makes the compiler believe we know what
// we're doing
// pointers are not arrays, even though they mostly behave similarly:
std::cout << sizeof(a) << ", " << sizeof(p) << ", " << sizeof(void*) << '\n';
// compare the int* size to void* size
}
而且例如它應用到指針到數組:
typedef int T[3];
void g(T a[3]);
// same as:
void g(T a[]); /*and*/ void g(T* a);
// that T happens to be an array type doesn't change anything, these are
// also declaring the same function:
void g(int a[][3]); /*and*/ void g(int (*a)[3]);
void f() {
int a[3][3] = {};
int* end = (int*)(&a + 1);
// note that end - &a[0][0] is 9
int* p = &a[0][0];
std::cout << sizeof(a) << ", " << sizeof(p) << ", " << sizeof(void*) << '\n';
}
重新加標籤的編程語言「C++」連接 - 它肯定看起來像C++如果不是,請更正。 – 2010-02-04 01:57:19