LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1200|回复: 15

pointer to structure有关的输出问题。

[复制链接]
发表于 2003-10-21 13:09:48 | 显示全部楼层 |阅读模式
关于红色的那行命令,它是不是要把int变量转志unsigned char*?
程序运行时,为什么
  1. cout<<"builder"<<endl;
复制代码
语句没有被执行?
  1. #include<iostream>
  2. using namespace std;

  3. typedef struct c_stash_tag {
  4.    unsigned char* storage_b;
  5. } c_stash;

  6. int main () //define variable at the beginning of the block, as in c:
  7. {
  8.    unsigned char* storage_a;
  9.    cout<<"storage_a="<<storage_a<<endl;
  10.    c_stash int_stash;
  11.    c_stash* s=&int_stash;
  12.    cout<<"s->storage_b="<<s->storage_b<<endl;
  13.    [color=red]s->storage_b=0;[/color]
  14.    cout<<"s->storage_b="<<s->storage_b<<endl;
  15.    cout<<"builder"<<endl;
  16. }
  17. [root@localhost c_lib_test_a]# ./c_lib_test_aa
  18. storage_a=8Z@
  19. s->storage_b=   B
  20. s->storage_b=[root@localhost c_lib_test_a]#
复制代码

谢谢.
发表于 2003-10-21 21:35:27 | 显示全部楼层
这里0 = NULL
 楼主| 发表于 2003-10-21 22:13:33 | 显示全部楼层
为什么
  1. cout<<"builder"<<endl;
复制代码
没有被执行呢?
发表于 2003-10-21 22:34:03 | 显示全部楼层
使用gdb跟看
发表于 2003-10-21 22:40:33 | 显示全部楼层
主要是前面输出了一个
cout << (unsigned char *)0;
如果你把main的第一行改成:
unsigned char* storage_a = 0;
那么后面的输出也都没有了,
至于为什么这样,我就不清楚了,没研究过这个问题
 楼主| 发表于 2003-10-22 08:25:46 | 显示全部楼层
谢谢指点。
发表于 2003-10-22 16:04:14 | 显示全部楼层
这会不会是终端缓冲区造成的问题?
发表于 2003-10-22 17:03:03 | 显示全部楼层
可能已经core dump了

c++中重载操作符是根据类型来重载的

如果代码内没有保护机制那么有可能core dump
 楼主| 发表于 2003-10-22 19:01:30 | 显示全部楼层
作为一名++的初学者,很荣幸大家对我提出的问题感兴趣。
quote from:
http://www.linuxquestions.org/qu ... amp;threadid=106915
  1. unsigned char* storage_a;
复制代码

这是一个dangling pointer (不好意思,我知道大多数人怎么翻译这个名词),
这个指针没有reference, 它试图把内存中的某处引领至stack,实际上stack中并没有它的信息,所以当我们试图获得这种指针的值时,程序崩溃。

我的问题:设,我把NULL赋值给两个没有reference的指针,pointer to int and pointer to char, 那么pinter to int的地址是:00000;pointer to char没有地址。这种观点对不对?

这里有一个程序:
  1. #include<iostream>
  2. using namespace std;

  3. int main ()
  4. {
  5.    unsigned char* uc;
  6.    uc=0;
  7.    unsigned int* ui;
  8.    ui=0;
  9.    double* ud;
  10.    ud=0;
  11.    cout<<"ui="<<ui<<endl;
  12.    cout<<"ud="<<ud<<endl;
  13.    cout<<"uc="<<uc<<endl;
  14.    cout<<"builder"<<endl;
  15. }
  16. [root@localhost c_lib_test_a]# ./c_lib_test_ai
  17. ui=0
  18. ud=0
  19. uc=[root@localhost c_lib_test_a]#
复制代码

这个程序中的两个指针,double* ud and unsigned int* ui 是否具有相同的地址:00000? 到目前为止,在那个论坛里,还没有人回答我的这几个问题,我总是在论坛里问一些比较简单的问题。

谢谢。
发表于 2003-10-23 12:23:54 | 显示全部楼层
跟第一个一样的道理

程序试从NULL地址读出
一个char 或是一个int或是一个double

但是这个地址不是进程的可以合法访问的地址
所以会产生内存保护异常

然后core dump
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表