在C++中创建指针时,系统将分配用来存储地址的内存,但不会分配用来存储指针所指向的数据的内存。如下所示代码,*p没有明确的指向,因为系统会将1放在任何一个合适的内存块中。
int *p;
*P=1;
cout<<"Please enter a number";
cin>>p;
对数组名应用取地址运算符&时,得到的是整个数组的地址,尽管从数字上看, 其与数组第一个元素的地址相同。但从概念上来说,二者是不同的。
3.
//创建大小未知的动态数组
int size;
cin >> size;
int *a=new int[size];
delete [] a; //new和delete要匹配
一般来说,给cout提供一个指针,它将打印地址。但如果指针类型为char*,则cout会输出指针指向的字符串。可以用类型转换来输出地址。此外,"ch=str1;"只是复制了字符串的地址,并未复制字符串。
#include <iostream>
int main()
{
using namespace std;
int *a=new int;
*a = 5;
char* ch;
char str1[20] = "string";
ch = str1;
cout << a << endl << ch<<endl
<<(int *)ch<<endl<<(long*)ch<<endl<<(float*)ch;
delete a; //new和delete要匹配
return 0;
}
5.
#include <iostream>
int main()
{
using namespace std;
char a = 'a';
cout << (int)a << endl;
cout << a++ << endl;
cout << ++a << endl;
cout << a + 1 << endl;
cout<< 1 + a;
return 0;
}
#include <iostream>
int main()
{
using namespace std;
int a = 99;
cout << a << endl << a++ << endl << ++a << endl << a + 1 << endl << 1 + a; //尽量不要这样书写
return 0;
}
6.右值引用
#include <iostream>
int main()
{
int x = 1;
int y = 1;
int&& r = x + y;
std::cout << r << std::endl;
x = 2;
y = 2;
std::cout << r << std::endl;
return 0;
}
7.字符串常量的行为与数组名相同
#include <iostream>
int main()
{
using std::cin;
using std::cout;
using std::endl;
const char* a = "abc";
cout << a << " "<<*a<<endl;
cout << *("abc") << endl;
for (int i = 0; i < 3; i++)
cout << "abc"[i] << endl;
return 0;
}