错误:初始化元素不是编译时常量

ziK*_*ouT 4 c static compiler-errors initialization compile-time-constant

我一直在寻找答案,但找不到任何可以运行此代码的内容。我得到av[1]的声明中main函数时,编译器强调:

static char const *str = av[1];
Run Code Online (Sandbox Code Playgroud)

这是我尝试使用 gcc 运行的代码:

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

char    *ft_strjoin(char const *s1, char const *s2);

void    fct(char **av)
{
    static char const *str = av[1];
    str = ft_strjoin(av[1], av[1]);
    printf("%s\n", str);
}

int main(int ac, char **av)
{
    fct(&av[1]);
    fct(&av[1]);
    fct(&av[1]);
    fct(&av[1]);
    fct(&av[1]);
    fct(&av[1]);
}
Run Code Online (Sandbox Code Playgroud)

我发现 很有趣,但我仍然不明白,也不知道如何运行这段代码。

Sou*_*osh 5

引用C11,第 6.7.9 节,初始化

具有静态或线程存储持续时间的对象的初始值设定项中的所有表达式应为常量表达式或字符串文字。

在您的代码中,

static char const *str = av[1];
Run Code Online (Sandbox Code Playgroud)

av[1]不是编译时常量值(即,不是常量表达式)。因此错误。

您需要删除staticfromstr以避免出现此问题。


hac*_*cks 2

static变量需要使用编译时常量(常量文字)进行初始化。av[1]将在运行时计算,这就是您收到错误消息的原因。