c/c++语言开发共享使用extern将数组与指针链接起来

假设我有两个文件:file1.c-包含一个名为“array [10]”的大小为10的int数组的全局定义。 file2.c-包含一个名为“extern int * array”的int指针,这里我试图将这个指针链接到数组。

但是当我检查file1.c中的数组地址和file2.c中的指针值时,它们都是不同的。 为什么会这样?

    这不起作用,在file2.c ,你需要

     extern int array[]; 

    因为数组和指针不是一回事。 两个声明必须具有兼容类型,并且int*int[N]不兼容。

    实际发生的事情没有指定,程序使用extern int *array; ,但可能,数组的第一个sizeof(int*)字节被解释为一个地址。

    extern1.c

     #include  extern int *array; int test(); int main(int argc, char *argv[]) { printf ("in main: array address = %xn", array); test(); return 0; } 

    extern2.c

     int array[10] = {1, 2, 3}; int test() { printf ("in test: array address = %xn", array); return 0; } 

    输出:

     in main: array address = 1 in test: array address = 804a040 

    汇编代码:

     08048404 
    : 8048404: 55 push %ebp 8048405: 89 e5 mov %esp,%ebp 8048407: 83 e4 f0 and $0xfffffff0,%esp 804840a: 83 ec 10 sub $0x10,%esp 804840d: 8b 15 40 a0 04 08 mov 0x804a040,%edx <--------- this (1) 8048413: b8 20 85 04 08 mov $0x8048520,%eax 8048418: 89 54 24 04 mov %edx,0x4(%esp) 804841c: 89 04 24 mov %eax,(%esp) 804841f: e8 dc fe ff ff call 8048300 8048424: e8 07 00 00 00 call 8048430 8048429: b8 00 00 00 00 mov $0x0,%eax 804842e: c9 leave 804842f: c3 ret 08048430 : 8048430: 55 push %ebp 8048431: 89 e5 mov %esp,%ebp 8048433: 83 ec 18 sub $0x18,%esp 8048436: c7 44 24 04 40 a0 04 movl $0x804a040,0x4(%esp) <------- this (2) 804843d: 08 804843e: c7 04 24 3d 85 04 08 movl $0x804853d,(%esp) 8048445: e8 b6 fe ff ff call 8048300 804844a: b8 00 00 00 00 mov $0x0,%eax 804844f: c9 leave 8048450: c3 ret

    注意汇编代码中的<-------。 您可以在main函数中看到数组是array [0],在测试函数中,数组是地址。

      以上就是c/c++开发分享使用extern将数组与指针链接起来相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549809.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐