错误:初始值设定项元素不是编译时常量 [英] error: initializer element is not a compile-time constant

查看:107
本文介绍了错误:初始值设定项元素不是编译时常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找答案,但找不到任何能使此代码运行的东西。声明时,在主函数中,编译器会突出显示 av [1]

I have been looking for answers but could not find anything to make this code run. I get av[1] highlighted by the compiler in the main function when declaring:

static char const *str = av[1];

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

Here is the code I tried to run with 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]);
}

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

I found this interesting but I still don't get it and don't know how to run this code.

推荐答案

引用 C11 ,第6.7.9节,初始化

Quoting C11, §6.7.9, Initialization


初始化程序中具有静态或线程存储持续时间
的对象的所有表达式均应为常量表达式

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

在您的代码中,

static char const *str = av[1];

av [1] 不是编译器时间常数值(即不是常数表达式)。因此出现错误。

av[1] is not a compile time constant value (i.e., not a constant expression). Hence the error.

您需要从 str 静态 c>避免出现此问题。

You need to remove static from str to avoid the issue.

这篇关于错误:初始值设定项元素不是编译时常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆