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

前端 未结 4 1604
执念已碎
执念已碎 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:31

    The first code is broken. The assignment

    int *c = &b;
    

    is invalid. The right-hand side has type int (*)[2], while the object on the left has type int *. These are different, incompatible types. The compiler should have told you about this error by issuing a diagnostic message. Don't ignore diagnostic messages issued by compilers.

    The code, despite suffering from the above problem, was accepted by the compiler due to a non-standard compiler extension, which allowed the compiler to convert int (*)[2] pointer to int * type preserving the numerical value of the pointer (the physical address). So, you ended up with int * pointer pointing to the beginning of your int [2] array. Not surprisingly, accessing memory through that pointer lets you to see the contents of the array.

    Your second code is also broken in more than one way. It doesn't suffer from the first problem, since you don't force any conversion of &b value (which, again, has type int (*)[2]) to anything else, but apply pointer arithmetic directly to &b. According to the rules of pointer arithmetic, the expression &b + 1 produces a pointer that points beyond the original b array. Dereferencing such pointer is illegal. So, *(&b + 1) already produces undefined behavior. On top of that, the expression *(&b + 1) has type int [2], which decays to pointer type int *. So, in your second code you are attempting to print an int * value with %d format specifier. This is also undefined behavior. The manifestations of that undefined behavior is what you see in your second example.

    In other words, in the first piece of code you got luckier than in the second one, which is why the output of the former looks more meaningful.

提交回复
热议问题