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!!!!

1
  • By the way you using C++. Because in C arrays and pointers are handled somehow the same (the size of a pointer and the sizeof your C string is different of course) the usual way to handle this kind of problem in C++ is to use a template class like std::vector. Commented Nov 28, 2012 at 4:09

4 Answers 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].

Sign up to request clarification or add additional context in comments.

1 Comment

I couldn't understand "Arrays are not pointers". Can I reframe it to "Arrays are not pointers but ArrayName is a pointer"?
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.

Comments

1

If you would like to use an array structure where the compiler checks the bounds of the array, you can use std::vector. For example

#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; 
}

Here, vec.at(i) checks the bounds of the vector. If you use vec[i], this is also valid but the compiler does not check the bounds. Hope that helps.

Comments

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?

1 Comment

**Why would the compiler treat it as an array?**Maybe it is because the char it points to is a member of an array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.