0

我想获取退出库函数的地址,然后将此地址分配给全局变量。

  //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 程序时出现了一个错误。

$ 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

当我在主函数中获取并分配出口地址给局部变量时,没有错误。

  //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

如何将出口地址分配给全局变量?

4

1 回答 1

3

您应该fp使用正确的类型声明(即指向一个函数的指针,它接受一个int并且什么都不返回):

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

不知道你想用printfthen 做什么。如果要打印地址,请使用%p而不是%d.

于 2013-07-24T11:41:10.163 回答