开发者

Perhaps a function pointer or casting problem. Not sure

开发者 https://www.devze.com 2023-01-11 18:12 出处:网络
What\'s happening in this code? I don\'t get this code. Looks like it\'s performin开发者_开发问答g some type of casting or using function pointers but I\'m not sure. Will appreciate if someone can hel

What's happening in this code? I don't get this code. Looks like it's performin开发者_开发问答g some type of casting or using function pointers but I'm not sure. Will appreciate if someone can help me. Thanks.

const char string[]="Hello!";

int main()   
{

    (*(void (*)()) string)(); //Obviously, my problem is this line :)

    return 0;
}


First, let's use cdecl to explain the inner gibberish:

$ cdecl
cdecl> explain (void (*)())
cast unknown_name into pointer to function returning void

So (void (*)()) string casts string into a function pointer. Then the function pointer is dereferenced to call the underlying function. The line is equivalent to

void (*fp)() = (*(void (*)()) string)();
(*fp)();

This (on most machines) tries to execute "Hello!" as machine code. It may crash outright on machines with virtual memory because data is often marked as non-executable. If it doesn't crash, it's not likely to do anything coherent. In any case, this is not useful code.

The only thing to learn here is that the cdecl tool can be useful to understand or write complicated C types and declarations.


void (*)() is a function pointer type. (void (*)()) string casts string to such a function pointer. The remaining (* ...)() in the expression dereferences this resulting function pointer and tries to call the function.

Since there isn't any function where that pointer points to, but only the string "Hello!", this won't lead to any useful results.

0

精彩评论

暂无评论...
验证码 换一张
取 消