Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error C2040: 'void *()' differs in levels of indirection from 'int ()'

Tags:

c

#include <stdio.h>

main()
{
    myfunction();
}

void* myfunction() {
    char *p;
    *p = 0;
    return (void*) &p;
}

When the program run at Visual Studio, it could not compile and the error message goes like below:

"Error 2 error C2040: 'myfunction' : 
'void *()' differs in levels of indirection from 'int ()' "

Could someone explain?

like image 997
user2085606 Avatar asked Oct 29 '25 16:10

user2085606


2 Answers

You should add the declaration of myfunction() before useing it in main() function:

void* myfunction(void);

int main(void)
{
    myfunction();
    return 0;
}

void* myfunction(void) {
    char *p;
    *p = 0;
    return (void*) &p;
}

try it.

like image 104
Nan Xiao Avatar answered Oct 31 '25 05:10

Nan Xiao


Your program has two problems. The first problem is the one mentioned in Nan Xiao's answer, whereby the compiler is assuming the signature of myfunction is int myfunction() upon seeing your call in main.

The second problem is you have incorrect levels of indirection inside myfunction itself:

void* myfunction(void) {
    char *p; // Create a pointer to a character
    *p = 0;  // Set some random location to zero
    return (void*) &p; // Take the address of the pointer to a character,
                       // and turn it into a pointer to anything
}

That is, your cast is taking char ** and making a void * with it, which is probably not what you wanted.

If you want to return the character pointer cast to a void pointer, just return the character pointer itself, without the cast.

like image 26
Billy ONeal Avatar answered Oct 31 '25 05:10

Billy ONeal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!