error: initializer element is not a compile-time c

2019-07-15 05:25发布

问题:

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];

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.

回答1:

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.

In your code,

static char const *str = av[1];

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

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



回答2:

static variables need to be initialised with a compile time constants (constant literals). av[1] will be calculated at runtime and that's why you are getting the error message.



回答3:

You could simulate that behaviour by writing:

static const char *str;
static bool already;
if ( !already )
{
    str = av[1];
    ++already;
}

However this would be redundant compared to the solution of:

const char *str;

because you immediately overwrite that value anyway with the return value of your function.

(Also you pass the same argument in every call, so even if you used str, it still doesn't need to be static).