What do these two C warnings mean exactly?
开发者_StackOverflow中文版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:
- /home/lk/proj/m3/m3_lolauncher/lolauncher.c(0,0): Warning: initialization from incompatible pointer type (m3_lolauncher)
- /home/lk/proj/m3/m3_lolauncher/lolauncher.c(0,0): Warning: excess elements in scalar initializer (m3_lolauncher)
I dont understand the first one as i cast correctly?
I've never seen the second one...
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;
}
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:
- initialization from incompatible pointer type (
m3_func**
!=m3_func*
) - excess elements in scalar initializer ( a pointer is a scalar, and you're trying to initialize it with two pointers -- ergo one excessive )
精彩评论