C编译器是否为变量分配内存?

Ris*_*hal 1 c

我想知道在哪个阶段,内存被分配给变量.它是在编译阶段还是在执行时?

Pau*_*vie 6

是的,是的,都是.

对于全局变量(在文件范围内声明),编译器在可执行映像中保留内存.所以这是编译时.

对于自动变量(在函数中声明),编译器添加指令以在堆栈上分配变量.所以这是运行时

int a;        // file scope

int f(void)
{
    int b;    // function scope
    ...
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 编译器有一(一组)指令一次性分配函数的所有局部变量.通常,每个变量没有开销(可能存在我现在不讨论的例外).每次调用函数时都会执行这些指令.

  • 编译器不为您的字符串分配存储空间.这是初学者经常犯的错误.考虑:

    char *s;         // a pointer to a strings
    scanf("%s", s);  // no, the compiler will not allocate storage for the string to read.
    
    Run Code Online (Sandbox Code Playgroud)