0

exit ライブラリ関数のアドレスを取得し、このアドレスをグローバル変数に割り当てます。

  //test3.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4   int fp = &exit;
  5 
  6 int main(){
  7   printf("fp=%d\n",fp);
  8   return 0;
  9 }

しかし、gcc を使用して上記の test3.c プログラムをコンパイルすると、1 つのエラーが発生します。

$ gcc -o test3 test3.c
test3.c:4:12: warning: initialization makes integer from pointer without a cast [enabled by default]
test3.c:4:3: error: initializer element is not computable at load time

exit のアドレスを取得して main 関数のローカル変数に代入すると、エラーは発生しません。

  //test4.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 int main(){
  5   int fp = &exit;
  6   printf("fp=%d\n",fp);
  7   return 0;
  8 }

結果を印刷できます:

$ gcc -o test4 test4.c
test4.c: In function ‘main’:
test4.c:5:12: warning: initialization makes integer from pointer without a cast [enabled by default]
$ ./test4
fp=4195408

exit のアドレスをグローバル変数に割り当てるにはどうすればよいですか?

4

1 に答える 1

3

正しい型で宣言する必要がfpあります (つまり、引数を取ってint何も返さない関数へのポインタ):

void (*fp)(int) = &exit;

あなたが何をしようとしているのかわからないprintf。住所を印刷したい場合は、%p代わりに%d.

于 2013-07-24T11:41:10.163 に答える