简体   繁体   中英

How can the compiler in C get the difference between the address of the first element of the array and the address of the whole array?

Given this problem and I'm fully aware of the facts of :

1) The name of an array is a fixed pointer to the first element of it.

2) The name of a 2D matrix is the address of the first 1D array of it.

3) and the difference between x[i] and &x[i] in arithmetic operations (where i is a non negative integer).

The compiler is MinGW How can the compiler in C get the difference between the address of the first element of the array and the address of the whole array although they hold the same numeric value ?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void)
{
    int x[3][3] = {1,2,3,4,5,6,7,8,9} ; 
    int *p  ; 
    for(p = &x[0] ; p < &x[0] + 1 ; p++) //Warning: comparison of distinct pointer types in this line of code 
        printf("%d\n",*p) ; 

    return 0 ; 
}

You're assigning / comparing two different pointer types.

x has type int [3][3] , ie an array of size 3 of an array of size 3 of int . From there, x[0] has type int [3] , ie array of size 3 of int .

Subsequently, &x[0] has type int (*)[3] , ie a pointer to an array of size 3 of int . In contrast, p has type int * , ie pointer to int . These are distinct types, which is why the compiler is giving you a warning.

The compiler parses expressions in more-or-less the manner I described, looking at the type of an object and seeing how the type of the resulting expression changes as each operator is applied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM