Chinaunix首页 | 论坛 | 博客
  • 博客访问: 310989
  • 博文数量: 42
  • 博客积分: 451
  • 博客等级: 下士
  • 技术积分: 890
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-03 18:24
文章分类

全部博文(42)

文章存档

2015年(1)

2013年(9)

2012年(19)

2011年(13)

分类: C/C++

2012-11-19 20:13:44


点击(此处)折叠或打开

  1. # cat a.c
  2. #include <stdio.h>
  3. #include "b.h"

  4. void main()
  5. {
  6.     struct stb *pb;
  7.     pb = set_b(1);
  8.     printf("%d\n", pb->i);
  9. }

点击(此处)折叠或打开

  1. # cat b.c
  2. #include <stdlib.h>
  3. #include "b.h"

  4. struct stb{
  5.     int i;
  6. };

  7. struct stb *set_b(int num)
  8. {
  9.     struct stb *pb = NULL;
  10.     pb = (struct stb*)calloc(1, sizeof(struct stb));
  11.     pb->i = num;
  12.     return pb;
  13. }

点击(此处)折叠或打开

  1. # cat b.h
  2. #ifndef __B_H
  3. #define __B_H

  4. struct stb *set_b(int i);
  5. #endif

点击(此处)折叠或打开

  1. # gcc a.c b.c
  2. a.c: In function 'main':
  3. a.c:8: error: dereferencing pointer to incomplete type
所有信息如上,文件a.c中的代码printf("%d\n", pb->i)试图访问pb指针内的数据,结果编译出错,提示pb指针指向的内存中未定义int i这个类型参数。给出指针地址,知道指针的类型,为什么访问不了里面的参数呢?首先来看看一个最简单的c代码:

点击(此处)折叠或打开

  1. # cat test.c

  2. void main()
  3. {
  4.     struct fjcasfas *p;
  5. }
fjcasfas是随手敲出的代码,此结构体从未被定义,子虚乌有,只在这里随便声明了一下。gcc test.c的结果是编译成功。编译器承认这个结构体指针的合法性,但是此时要是试图访问指针里面的内容(比如p->i),显然会编译出错。

回到a.c代码,对编译起来说,struct stb *pb也仅仅是声明出来的变量,想要在a.c文件中访问里面的参数,门儿都没有。

解决方法是在b.c文件中访问pb指向的内存的参数,代码如下:

点击(此处)折叠或打开

  1. # cat a.c
  2. #include <stdio.h>
  3. #include "b.h"

  4. void main()
  5. {
  6.     struct stb *pb;
  7.     pb = set_b(1);
  8.     PRINT_PB(pb);
  9. }

  10. # cat b.c
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include "b.h"

  14. struct stb{
  15.     int i;
  16. };

  17. struct stb *set_b(int num)
  18. {
  19.     struct stb *pb = NULL;
  20.     pb = (struct stb*)calloc(1, sizeof(struct stb));
  21.     pb->i = num;
  22.     return pb;
  23. }

  24. void PRINT_PB(struct stb *p)
  25. {
  26.     printf("%d\n", p->i);
  27. }

  28. # cat b.h
  29. #ifndef __B_H
  30. #define __B_H

  31. struct stb *set_b(int i);
  32. void PRINT_PB(struct stb *p);
  33. #endif
执行结果:

点击(此处)折叠或打开

  1. # gcc a.c b.c
  2. # ./a.out
  3. 1


阅读(1867) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~