1-p是指针,是地址;
int *P;2-编程习惯,空格位置
int *p;//这里强调*p是一个int类型的变量,C程序员经常使用这种形式 int* p;//这里强调int*是一个类型,用来定义指向int的指针 int* p1,p2;//这样创建的是一个指针,一个int型变量;因为一个指针需要一个*3-C语言中可以使用malloc分配内存,C++中可以还可以使用New来分配内存
int *pn = new int;//返回所配内存的首地址4-只能用delete释放由new分配的内存 如何使用调用动态数组中的元素?
//使用new来创建动态数组 int *p=new int [10];//返回所配内存的首地址 delete [] p;//释放内存 int *pn = new int [10]; pn[0] = 3; pn[1] = 4; pn[2]=5; cout << pn[0] << " " << pn[1] << endl; pn=pn+1; //指针指向第二个地址 cout << pn[0] << " " << pn[1] << endl; /*输出结果: 3 4 4 55-指针和字符串 注意:cout语句中 f 是代表字符“r"的地址,cout会从字符 r 开始输出字符串,一直遇到 '/0’为止; 此外,对于数组中的字符串、指针代表的字符串、双引号代表的字符串常量,cout都是用来传递其地址,而不是传递字符串,
char f[10] = "rose"; cout << f << " is red"; /**输出结果 rose is red /6-显示字符串的地址 为什么用(int )animal显示字符串地址,而不是用(char )animal来显示字符串的地址? 答:要显示字符串的地址,则必须将这种指针(char类型)转化成另一种指针类型,如int 或者double
char animal[20] = "bear";//数组存储字符串 const char *bird = "wren";//指针存储字符串 char *ps; cout << animal << " and "; cout << bird << endl; cout << "enter an kind of animal"; cin >> animal;//输入fox ps=animal; cout<<animal<<" at "<<(int *)animal<<endl;//用来显示字符串的地址 cout<<ps<< " at "<<(int*)ps<<endl;7-使用new创建动态结构
//使用new创建动态结构 struct inflatable { char name[20]; float volume; double price; }; inflatable *p = new inflatable;//使用new创建动态结构 cout << "enter name of inflatable item" << endl; cin.get(p->name, 20);//第一种输入方法 cout << "enter a volume" << endl; cin >> (*p).volume;//第二种输入方法 cout << "enter the price" << endl; cin >> p->price; cout << "name: " << p->name << " volume: " << p->volume <<" price: "<<p->price<< endl; /* 输出结果 enter name of inflatable item kevin enter a volume 100 enter the price 400 name: kevin volume: 100 price: 400 */8-new和delete的一个小例子 //使用new和delete管理内存(管理字符串) /如果要输入100个字符串,其中最长的字符串为79个字符, 而大多数字符串短的多, **方法一:**如果要用char数组来存储这些字符串, 需要100个数组,其中每个数组的长度为80个字符。这样其实有很多内存没有被使用 **方法二:**创建一个数组,它包含100个指向char的指针,然后使用new 根据每个字符串的需要分配相应的内存
//创建函数 char *getname() { char name[80]; char *p; cout << "enter your name: " << endl; cin >> name; p = new char[strlen(name) + 1]; //p = name;//这是错误的,因为这样只是修改了存储在p中的地址 strcpy(p,name);//在visual stdio 2013中出现错误,还没有解决 return p;注意:为什么要使用new来创建一个指针,为什么不直接返回name 地址呢? 答:因为name为“自动存储”,只有在函数getname()活动时存在,当在main()函数中便将name的内存释放了;
9-存储 1-自动存储 2-静态存储 静态存储:1-在函数外面定义;2-在声明变量时,使用关键字static; 3-动态存储 使用new和delete来管理内存,成为自由存储空间或者堆(heap)
