imacake
imacake

Reputation: 1713

What do these two C warnings mean exactly?

have the following C code:

typedef void*(m3_func)(void);
#define NULL ((void*)0)

char* lolinfo()
{
    return "You got the additional info! :D";
}

m3_func** m3_funcs() {
    return (m3_func**) {
        (m3_func*)(&lolinfo), // warning #1
        NULL
    }; // warning #2
}

I'm getting these warnings:

I dont understand the first one as i cast correctly?

I've never seen the second one...

Upvotes: 1

Views: 171

Answers (2)

Adrien Plisson
Adrien Plisson

Reputation: 23303

it seems your sample code is not valid C.

if i understand your code, the m3_funcs() function should return a NULL terminated array of function pointers. you are actually trying to use an initializer ({...}) to declare an array and return it right away. but i don't think you can use an initializer outside of a variable declaration... also, note that this "variable" would exists only in the context of the m3_funcs() call, so the address that might eventually be returned would no more be valid after the function has returned.

the correct way to implement such a feature is to have a static global variable, and return its address:

static m3_func *m3_funcs_array[] = {(m3_func *)&lolinfo, NULL};

m3_func ** m3_funcs()
{
    return &m3_funcs_array;
}

Upvotes: 3

Kornel Kisielewicz
Kornel Kisielewicz

Reputation: 57555

A list initialization would be:

a = { b,c,d }

What you are doing here is using the new universal initialization (x{y}). Hence, you're trying to initialize a single m3_func** pointer with two m3_func* pointers. Ergo you have two warnings:

  1. initialization from incompatible pointer type ( m3_func** != m3_func* )
  2. excess elements in scalar initializer ( a pointer is a scalar, and you're trying to initialize it with two pointers -- ergo one excessive )

Upvotes: 1

Related Questions