指针 指针和地址容易弄混,特别是在数组中,c++中有许多的差别,先来看一串代码!
// addpntrs.cpp -- pointer addition
#include
int main()
{
using namespace std;
double wages[3] = {10000.0, 20000.0, 30000.0};
short stacks[3] = {3, 2, 1};
// Here are two ways to get the address of an array
double * pw = wages; // name of an array = address
short * ps = &stacks[0]; // or use address operator
// with array element
cout << "pw = " << pw << ", *pw = " << *pw << endl;
pw = pw + 1;
cout << "add 1 to the pw pointer:\n";
cout << "pw = " << pw << ", *pw = " << *pw << "\n\n";
cout << "ps = " << ps << ", *ps = " << *ps << endl;
ps = ps + 1;
cout << "add 1 to the ps pointer:\n";
cout << "ps = " << ps << ", *ps = " << *ps << "\n\n";
cout << "access two elements with array notation\n";
cout << "stacks[0] = " << stacks[0]
<< ", stacks[1] = " << stacks[1] << endl;
cout << "access two elements with pointer notation\n";
cout << "*stacks = " << *stacks
<< ", *(stacks + 1) = " << *(stacks + 1) << endl;
cout << sizeof(wages) << " = size of wages array\n";
cout << sizeof(pw) << " = size of pw pointer\n";
return 0;
}
下面是输出
pw = 0x28ccf0, *pw = 10000
add 1 to the pw pointer:
pw = 0x28ccf8, *pw = 20000
ps = 0x28ccea, *ps = 3
add 1 to the ps pointer:
ps = 0x28ccec, *ps = 2
access two elements with array notation
stacks[0] = 3, stacks[1] = 2
access two elements with pointer notation
*stacks = 3, *(stacks + 1) = 2
24 = size of wages array
4 = size of pw pointer
我们注意wages pw字节数存在差异 size(pw)是第一个元素的内存,但size(wages)却是整个数组的内存!! 地址有异曲同工之妙。
来看一串指针表示法,我们对于结构与指针的关系会更加了解。
#include
struct inflatable
{
char name[20];
float volume;
double price;
};
using namespace std;
int main()
{
inflatable* ps = new inflatable;
cout << "enter name of inflatable item:";
cin.get(ps->name, 20);
cout << "enter volume in cubic feet:";
cin >> (*ps).volume;
cout << "enter priace: $";
cin >> ps->price;
cout << "name:" << (*ps).name << endl;
cout << "volume:" << ps->volume << " cubic feet\n";
cout << "price: $" << ps->price << endl;
delete ps;
return 0;
}
我们程序员撸代码过程中,用new的时候切记要加delete释放内存,不然会引发严重后果。
下面这一串代码通过指针,new,delete节省内存。
// delete.cpp -- using the delete operator
#include
#include // or string.h
using namespace std;
char * getname(void); // function prototype
int main()
{
char * name; // create pointer but no storage
name = getname(); // assign address of string to name
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed
name = getname(); // reuse freed memory
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed again
return 0;
}
char * getname() // return pointer to new string
{
char temp[80]; // temporary storage
cout << "Enter last name: ";
cin >> temp;
char * pn = new char[strlen(temp) + 1];
strcpy(pn, temp); // copy string into smaller space
return pn; // temp lost when function ends
}
输出如下
Enter last name: Fredeldumpkin
Fredeldumpkin at 0x004326b8
Enter last name: Pook
Pook at 0x004301c8
这种设计的函数很节省内存,我们可以加以学习与模仿。
通过指针更加方便利用new,delete动态存储,会给程序减轻负荷,减少内存。 值得推荐。