extern declaration, T* v/s T[]

后端 未结 3 948
一向
一向 2020-12-15 00:56

I saw following piece of code in a legacy project.

/* token.c */
struct token id_tokens[MAX_TOKENS];

/* analyse.c (v1) */
extern struct token *id_tokens; /*         


        
3条回答
  •  孤城傲影
    2020-12-15 01:33

    lets understand same stuff by program

    test.c

    #include
    #include"head.h"
    struct token id_tokens[10];
    int main()
    {
    printf("In original file: %p",id_tokens);
    testing();
    }
    

    head.h

    struct token {
    int temp;
    };
    

    test1.c with v1

    #include
    #include"head.h"
    extern struct token* id_tokens;
    void testing () {
    printf("In other file %p",id_tokens);
    }
    

    Output : In original file: 0x601040In other file (nil)


    test1.c with v2

    #include
    #include"head.h"
    extern struct token id_tokens[];
    void testing () {
    printf("In other file %p",id_tokens);
    }
    

    Output : In original file: 0x601040In other file 0x601040


    This clearly shows that v1 is not correct and v2 is correct.

提交回复
热议问题