Last active
May 27, 2021 13:35
-
-
Save recuraki/78df6d3a0878afeb838b2fc048493d0e to your computer and use it in GitHub Desktop.
pointer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
long func(int x) { return x + 1; } | |
long func2(int x) { return x + 2; } | |
int main() { | |
// 64bitの場合、関数は64bitなのでlongにする | |
long a, b; | |
long (*c)(long); // 正しい関数ポインタ | |
// まず、定義したfuncのアドレスを調べる | |
printf("func value is %lx\n", func); | |
printf("func2 value is %lx\n", func2); | |
// 普通にfuncを呼んでみる | |
a = func(10); | |
printf("a = func(10) then a == %ld\n", a); | |
// aにfunc自身が代入できてしまう | |
a = func; | |
printf("a = func then a == %lx\n", a); // a == funcになる | |
// C言語にa = long を無理やり関数に解釈させる。 | |
b = ((long (*)(long)) a)(10); | |
printf("b = ((int (*)()) a)(10) then b == %ld\n", b); // func(10)と等価 | |
// 普通の関数ポインタの使い方。cに関数を代入 | |
c = func; b = c(100); | |
printf("c=func then c(100) = %l, (c value is %lx)\n", b, c); // func(10) | |
c = func2; b = c(100); | |
printf("c=func2 then c(100) = %l, (c value is %lx)\n", b, c); // func2(10) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment