4.8
如果给cout提供一个字符的地址,则他将从该字符开始打印,直到遇到空字符为止。
1 #include<iostream> 2 #include<cstring> 3 int main() 4 { 5 using namespace std; 6 char animal[20]="bear"; 7 const char*bird="wren"; 8 char *ps; 9 10 cout<<animal<<" and "<<bird<<endl; 11 12 cout<<"enter a kind of animal"; 13 cin>>animal; 14 15 ps=animal; 16 cout<<ps<<endl; 17 18 cout<<"before using strcpy()"<<endl; 19 cout<<animal<<" at "<<(int*)animal<<endl;//地Ì?址¡¤ 20 cout<<ps<<" at "<<(int*)ps<<endl; 21 22 ps=new char[strlen(animal)+1]; 23 strcpy(ps,animal); 24 25 cout<<"after using strcpy()"<<endl; 26 cout<<animal<<" at "<<(int*)animal<<endl; 27 cout<<ps<<" at "<<(int*)ps<<endl; 28 29 delete[] ps; 30 return 0; 31 }
应使用strcpy()或strncpy()而不是赋值运算符来将字符串赋给数组。
使用new创建动态结构
创建结构
inflatable *ps=new inflatable;
这将把足以存储inflatable结构的一块可用内存的地址赋给ps。
箭头运算符 ->
如果结构标识符是结构名,就用句点运算符。如果标识符是指针,就用箭头运算符。
1 #include<iostream> 2 struct inflatable 3 { 4 char name[20]; 5 float volume; 6 double price; 7 }; 8 9 int main() 10 { 11 using namespace std; 12 inflatable *ps=new inflatable; 13 cout<<"enter name of inflatable item"; 14 cin.get(ps->name,20); 15 cout<<"enter volume in cubic feet"; 16 cin>>(*ps).volume; 17 cout<<"enter price"; 18 cin>>ps->price; 19 cout<<"name:"<<(*ps).name<<endl<<"volume:"<<ps->volume<<endl<<"price:"<<ps->price<<endl; 20 return 0; 21 }
一个new和delete的实例
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 char *getname(); 5 int main() 6 { 7 char *name; 8 9 name=getname(); 10 cout<<name<<" at "<<(int*)name<<endl; 11 delete []name; 12 13 name=getname(); 14 cout<<name<<" at "<<(int*)name<<endl; 15 delete []name; 16 17 return 0; 18 } 19 20 char *getname() 21 { 22 char temp[80]; 23 cout<<"enter last name"; 24 cin>>temp; 25 char *pn=new char[strlen(temp)+1]; 26 strcpy(pn,temp); 27 return pn; 28 }
将new和delete放在不同的函数中不是一个好方法,容易忘掉使用delete。