gpt4 book ai didi

C语言在main()内部、main()外部初始化全局变量

转载 作者:行者123 更新时间:2023-11-30 18:33:02 25 4
gpt4 key购买 nike

  1. main() 内部——没有错误

    #include <stdio.h>
    #include <stdlib.h>

    #define MAX 4

    typedef struct
    {
    int vertex;
    int **matrix;
    }graph;
    graph ygraph={.vertex=MAX};

    int main()
    {
    ygraph.matrix=(int**)malloc(sizeof(int)*MAX*MAX);
    return 0;
    }
  2. main() 之外 -- 错误//

    #include <stdio.h>
    #include <stdlib.h>

    #define MAX 4

    typedef struct
    {
    int vertex;
    int **matrix;
    }graph;
    graph ygraph={.vertex=MAX};
    ygraph.matrix=(int**)malloc(sizeof(int)*MAX*MAX);

    int main()
    {
    return 0;
    }

有什么区别...?我无法在 main() 之外初始化全局变量?我认为两者都没有错误...

最佳答案

引用a passage来自 cppreference.com 上的 C 引用:

When initializing an object of static or thread-local storage duration, every expression in the initializer must be a constant expression or string literal.

静态对象(例如graph)的初始化器必须在编译时已知,因为这些变量的初始化内存是在编译器生成的对象文件中找到的。因此,它们不能包含函数调用。

$ cat a.c
int a = 7;
int b = 8;
int c = 9;

$ gcc -c a.c

$ objdump -t -s -j .data a.o

a.o: file format elf64-x86-64

SYMBOL TABLE:
0000000000000000 l d .data 0000000000000000 .data
0000000000000000 g O .data 0000000000000004 a
0000000000000004 g O .data 0000000000000004 b
0000000000000008 g O .data 0000000000000004 c


Contents of section .data:
0000 07000000 08000000 09000000 ............

函数中的赋值在调用函数期间进行评估(如果有的话),因此可能包含函数调用。

关于C语言在main()内部、main()外部初始化全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59854954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com