1. 关于"eng" 与其他类型在new时的不同点:
#include<iostream> #include<string> using namespace std; int main() { /*char* lang = "eng"; cout<<lang<<endl;*/ ok的,因为会给编译器会给"eng"自动分配数据存储空间,并返回字符串的首个char的地址(数据与地址关联)。并且由于cout及其他表达式看见字符串的char的首地址后,会读取整个字符串,直至遇到" "为止。 int* ptr = 10; cout<<*ptr<<endl;//没有初始化数据存储空间,所以会报错 return 0; }
2.
#include<iostream> #include<string> using namespace std; int main() { char flower[10] = "rose"; cout<<flower<<"s are red "<<endl;//cout及多数c++表达式中,char数组名,char指针以及用""括的字符串常量都被解释为字符串的第一个字符的地址,并且由于cout及其他表达式看见字符串的char的首地址后,会读取整个字符串,直至遇到" "为止。
return 0; }
3.
#include<iostream> #include<string> using namespace std; int main() { char* ps; cin >> ps;//使用了未初始化数据存储空间的指针,会报错 cout<<ps<<endl; return 0; }
4.
#include<iostream> #include<string> using namespace std; int main() { int a[10]; cout<<sizeof(a)<<endl;//40,对数组名使用sizeof(),得到的是数组占用的bytes数 cout <<sizeof(a)/sizeof(int) << endl;//10,得到的是数组长度; cout <<a<<endl;//000000C7119BF9E0,得到的是首个元素的地址 cout<<&a<<endl;//000000C7119BF9E0, 得到的是整个数组的地址,从数字上来说,两个地址相同,但a+1向后移动bytes of int位,而&a+1向后移动整个数组位! int (*b)[10] = &a;//注意此处必须为(* name)的形式,存储的是指针数组。 cout<<b[0]<<endl;//b[0]就是a,是个地址 return 0; }
5.
#include<iostream> #include<string> using namespace std; int main() { int* a = new int[3]; cout << sizeof(a)<< endl;//获取整形指针的size cout << _msize(a)/sizeof(int) << endl;//获取开辟给动态数组的长度 delete[] a; return 0; }
6.
#include<iostream> #include<string> using namespace std; int main() { char food[20] = "carrot"; cout << food << endl; strcpy_s(food, "flan"); cout<<food<<endl; strcpy(food, "flansdfljsdlfjsdjfieijskldfjlkk");//危险操作,会将超过的部分复制到数组后面的内存字节中,可能会覆盖其他正在使用的内存,不推荐 //推荐使用下列方法 strncpy(food, "flansdfljsdlfjsdjfieijskldfjlkk",19); food[19] = ' '; cout<<food<<endl; return 0; }