大头
Table_bottom

标签云
Table_bottom

分类
Table_bottom

日历
五月
2829301234
567891011
12131415161718
19202122232425
2627282930311
Table_bottom

评论
Table_bottom

留言
Table_bottom

微博
Table_bottom

热门文章
Table_bottom

随机文章
Table_bottom

豆瓣上谁关注这里
Table_bottom

链接
Table_bottom

搜索栏
Table_bottom

RSS
RSS Link
Table_bottom

功能
Table_bottom

页面
Table_bottom

计数器
474949
Table_bottom

访客统计
Table_bottom

存档
Table_bottom

外部变量申明的一个错误

loveisbug posted @ 2008年5月03日 21:25 in 学习 with tags c/c++ , 3401 阅读

C++中的外部变量不是类型安全的变量。

File: sub.cpp 

  1. // the string to print
  2. char str[] = "Hello World!\n";

 File: main.cpp 

  1. #include <iostream>
  2.  
  3. extern char *str; // the string to print
  4.  
  5. int main()
  6. {
  7.     std::cout<< str << std::endl;
  8.     return (0);
  9. }

 在这里,str被认为是一个指针,程序运行到那儿,读其地址前4位,而前4位是“Hell”,不是一个地址,所以出错。

Avatar_small
爱德丝 说:
2008年5月03日 22:27 奇怪了,为什么不把两个文件中的 str 声明为相同的类型
Avatar_small
大头 说:
2008年5月04日 01:19 是啊,错误往往是不可预料的。
Avatar_small
Li Yanrui 说:
2008年9月23日 06:12

这是典型的指针与数组概念混淆的例子,可参考 Expert C Programming.

Avatar_small
大头 说:
2008年9月25日 02:38

嗯,随时准备开始读这本书。

Avatar_small
一碗鸡蛋壳 说:
2008年10月08日 22:09

这样的代码能通过编译? 类型不一样的啊

Avatar_small
大头 说:
2008年10月08日 22:26

我没试过,你可以试一下。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter