0
char c='c';
char *pc = &c;
char a[]="123456789";
char *p = &(a[1]); 
cout <<"the size of the a: "<< sizeof (a)<< endl; //10
cout <<"the size of the p: "<< sizeof (p)<< endl; //4
cout << p[100] <<endl;//cross boundary intentionally
cout << pc[0];//c
cout << pc[1];

Compiler no longer treat the p as an array? how does compiler verify whether it is or not an Array? Is there any difference between p and pc ?

Thanks!!!!

4

4 回答 4

1

Compiler no longer treat the p as an array?

It never treated it as an array, because it was not. It was always a pointer. Arrays are not pointers. Read this, accept it, embrace it! They sometimes decay into pointers (when passed as parameters), but they are not pointers.

Is there any difference between p and pc ?

Type-wise - no. There's a difference in that they point to different chars.

Also, pc[1] is undefined behavior. You only own the memory pc points to directly - i.e. a single byte that contains the character 'c'. Same goes for p[100].

于 2012-11-28T04:06:14.383 回答
1

The compiler treats as arrays only variables declared as arrays, i.e. with square brackets. Pointers are not arrays, though, although you can treat array names as if they were pointers for the purposes of constructing pointer expressions.

于 2012-11-28T04:10:48.807 回答
1

如果您想使用编译器检查数组边界的数组结构,您可以使用std::vector. 例如

#include <vector>

int main()
{
    int array[]={0,1,2,3,4,5};
    std::vector<int> vec;
    vec.assign(array, array+6);

    for(unsigned int i=0; i<vec.size(); ++i)
    {
         std::cout << vec.at(i);
    }

    return 0; 
}

在这里,vec.at(i) 检查向量的边界。如果使用 vec[i],这也是有效的,但编译器不检查边界。希望有帮助。

于 2012-11-28T07:59:31.390 回答
0

The compiler cannot and will not treat p as an array. p is just a pointer to a char to which any address can be assigned. Why would the compiler treat it as an array?

于 2012-11-28T04:07:24.773 回答