首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新手求解C++PrimerPlus里的复合类型和指针有关问题

2013-04-26 
新手求解C++PrimerPlus里的复合类型和指针问题第四章复合类型里数组的地址完全搞不懂文章里这样写的数组名

新手求解C++PrimerPlus里的复合类型和指针问题
第四章复合类型里数组的地址完全搞不懂
文章里这样写的
数组名被解释为其第一个元素的地址,而对数组名应用地址运算符时,得到的是整个数组的地址:
short tell[10]; //tell an array of 20 bytes
cout<<tell<<endl; //displays&tell[0]
cout<<&tell<<endl; //displays address of whole array
从数字上说,这两个地址相同;但从概念上说&tell[0](即tell)是一个2字节内存块的地址,而&trll是一个20字节的内存块地址.因此,表达式tell+1将地址值+2,而表达式&tell+2将地址加20.换句话说,tell是一个shrot指针(*short),而&tell是一个这样的指针,即指向包含20个元素的short数组(short(*)[20]).

short不是一个2字节的内存块地址吗?为什么&tell+2将地址加20???
tell应该是tell[0]内存地址把
&tell=tell[10]整个数组的地址吗
是不是用11个内存地址来存储tell数组,头大啊.

注释是我的个人理解,不知道是不是对的求解.
#include <iostream>
#include <string>
//#include <cstring>
using namespace std;
int main()
{
char animal[20]="bear";  
const char *bird="wren"; //编译器将字符串存储进内存并将内存地址交给指针*bird
char *ps;  //空指针

cout<<animal<<" and "<<bird<<endl; //数组名animal为数组animal[0]的内存地址,cout从animal[0]内存地址读取字符直到读到空字符
//cout<<ps<<endl;
cout<<"输入到animal数组:"; 
cin>>animal; //输入字符串到animal,输入FOX将在animal[3]添加\0空字符

ps=animal; //用4字节存储animal[0]的内存地址
cout<<ps<<endl; //从animal[0]的内存地址读取FOX直到空字符\0
cout<<"使用strcpy()前:"<<endl;
cout<<animal<<" at "<<(int *)animal<<" "<<(double *)animal<<endl; //不能理解(int *)animal,个人猜测是不是将内存地址整数化,cout读取的是用4字节存储内存地址的整数???????
cout<<ps<<" at "<<(int *)ps<<endl;

ps=new char[strlen(animal)+1];
strcpy(ps,animal);
cout<<"使用strcpy()后:"<<endl;
cout<<animal<<" at "<<(int *)animal<<endl;
cout<<ps<<" at "<<(int *)ps<<" "<<(int *)animal[1]<<endl;
cout<<"ps大小="<<sizeof(ps)<<" animal大小="<<sizeof(animal)<<" (double *)animal大小="<<sizeof((short *)animal)<<endl;
system("pause");
delete []ps;
return 0;
}
C++ 指针 存储 内存
[解决办法]
short不是一个2字节的内存块地址吗?为什么&tell+2将地址加20???
加40,因为&tell,那么指针类型是tell[10],长度是20,+2就是40了
 tell应该是tell[0]内存地址把
是的
 &tell=tell[10]整个数组的地址吗
显然不是,而且是个危险地址了。
 是不是用11个内存地址来存储tell数组,头大啊.
不是,是10个
[解决办法]
cout<<animal<<" at "<<(int *)animal<<" "<<(double *)animal<<endl; //不能理解(int *)animal,个人猜测是不是将内存地址整数化,cout读取的是用4字节存储内存地址的整数???????
是的

热点排行