做个笔记,如果有错误,恳请路过的各位朋友指出,小弟感激不尽。
1.数组名字加1需要注意的事项。
#include <iostream.h>
int main(int argc, char* argv[])
{
int a[5] = {1,2,3,4,5};
int lena;
int lenp;
int *p = a;
lena = sizeof(a);
lenp = sizeof(p);
int *q = (int *)(&a+1);//q指向数组a的下一维,因为指针的加1运算,是与指针类型有关的。也即,此处&a是一个指针,其类型
//为指向一个5个元素的整形数组。 因此&a+1的值为a[5]的地址。必须将其强制转化为整型指针。
//int *q2 = &a + 1; //提示错误:指针类型不匹配,需要强制转化指针类型,绕过编译器检查。
cout << "the size of a: " << lena << endl;
cout << "the size of the pointer p :" << lenp << endl;
cout << "the address of a: " << &a << endl;
cout << "the address of a[1]: " << &a[1] << endl;
cout << "the address of p: " << p << endl;
cout << "the address of q: " << q << endl;
cout << "the address of &a + 1: " << (&a+1) << endl;
cout << "the address of a+1: " << a+1 << endl;
cout << "the value of *(q-1): " << *(q-1) << endl;//指针q的类型为整型指针,q-1是按4个字节的大小来计算。
return 0;
}
结果:
the size of a: 20
the size of the pointer p :4
the address of a: 0x0012FF6C
the address of a[1]: 0x0012FF70
the address of p: 0x0012FF6C
the address of q: 0x0012FF80
the address of &a + 1: 0x0012FF80
the address of a+1: 0x0012FF70
the value of *(q-1): 5
Press any key to continue
比较奇怪的是,VC++6.0调试时,用变量查看器(不知道确切的名字,姑且这么叫吧,*^__^*))查看,&a+1的值并不是上面所讲的那样,而是在a[0]的地址上加1。即如果a:0x0012FF6C,那么a[0]:0x0012FF6C,&a+1的结果为0x0012FF6D。
2.数组指针的退化
#include <iostream.h>
void test_array(int *arry);
int main(int argc, char* argv[])
{
int a[5] = {1,2,3,4,5};
int lena;
lena = sizeof(a);
cout << "the size of a in main: " << lena << endl;
test_array(a);//实参a初始化形参arry.
return 0;
}
void test_array(int *arry)
{
int len = sizeof(arry);//此时数组退化为正常的整型指针变量。可以看出,将数组传递给子函数时,子函数中的并不知道数组的维数。
cout << "the size of a in test_array: " << len << endl;
}
结果:
the size of a in main: 20
the size of a in test_array: 4
Press any key to continue