user163911
user163911

Reputation: 189

Why am I getting an initialization from incompatible pointer type warning?

So I'm using gcc on Linux and have the following two code snippets in separate files (only relaveant sections of code included):

int main()
{
    /* Code removed */
    int_pair_list *decomp = prime_decomp(N);
    if (decomp)
        while(decomp->next)
            decomp = decomp->next;
    printf("%d\n" decomp->value_0);
}

int_pair_list *prime_decomp(unsigned int n)
{
    int_pair_list *head = malloc(sizeof(*head));
    int_pair_list *current;
    /* method body removed, current and head remain as int_pair_list pointers */
    return current ? head : NULL;
}

The program compiles and runs correctly but, during compilation, I get the warning:

problem_003.c: In function ‘main’:
problem_003.c:7:26: warning: initialization from incompatible pointer type [enabled by default]
  int_pair_list *decomp = prime_decomp(N);
                      ^

I'm new to C and I just can't work out why I'm getting this warning.

Upvotes: 2

Views: 17237

Answers (1)

Eugene Sh.
Eugene Sh.

Reputation: 18331

In C a function (or it's prototype) should be declared before it is used in order to determine the correct signature of it. Otherwise the compiler will try to "guess" the correct signature. While it can infer the parameter types from the call, it is not the case with return value type, which is defaulting to int. In your code the function wasn't prototyped prior the usage, so the compiler is assuming it is returning int. This is the reason it is warning you about incompatible type assignment.

Upvotes: 3

Related Questions