error: initializer element is not a compile-time constant

ziKmouT picture ziKmouT · Dec 24, 2015 · Viewed 17.6k times · Source

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.

Answer

Sourav Ghosh picture Sourav Ghosh · Dec 24, 2015

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.