Inconsistency in using pointer to an array and address of an array directly

前端 未结 4 1644
执念已碎
执念已碎 2020-12-06 07:08

This code sample prints the array correctly.

int b[2] = {1, 2};
int *c = &b;
int  i, j,k = 0;
for (i = 0;i < 2; i++) {
    printf(\"%d \", *(c+i));
}
         


        
4条回答
  •  渐次进展
    2020-12-06 07:37

    int *c = &b;     
    

    This is actually not valid. You need a cast.

    int *c = (int *) &b; 
    

    The two expressions:

     *(c+i)
    
     and 
    
     *(&b+i)
    

    are not same. In the first expression i is added to a int * and in the second expression i is added to a int (*)[2]. With int *c = (int *) &b; you convert a int (*)[2] to an int *. c + i points to the i-th int element of c but &b+i points to the int [2] element of b moving the pointer value outside the actual array object.

提交回复
热议问题