Pointer Compatibility

The rules for assigning one pointer to another are tighter than rules for numeric types. For example, you can assign an int value to a double variable without using a type convertion, but you can't do the same for pointers to these two types:

int n = 5;
double x;
int * p1 = &n;
double * pd = &x;
x = n;  // implicit type conversion
pd = p1;  // compile-time error

These restrictions extend to more complex types. Suppose we have the following declarations:

int * pt;
int (*pa)[3];
int ar1[2][3];
int ar2[3][2];
int **p2;      // a ppinter to a pointer

The we have the following:

pt = &ar1[0][0];  // both pointer-to-int
pt = ar1[0];  // both pointer-to-int
pt = ar1;   // not valid
pa = ar1;   // both ponter-to-int[3]
pa = ar2;   // not valid
p2 = &pt;   // both pointer-to-int *
*p2 = ar2[0];  // both pointer-to-int
p2 = ar2;    // not valid

Notice that the nonvalid assignments all involve two pointers that don't point to the same type.

In general, multiple indirction is tricky. For instance, consider the next snippet of code:

int * p1;
const int * p2;
const int ** pp2;

p1 = p2;  // not valid -- assigning const to no-const
p2 = p1;  // valid -- assigning non-const to const
pp2= &p1; // not valid -- assigning non-const to const


你可能感兴趣的:(Pointer Compatibility)