工作积累之二维数组的理解

来源:互联网 发布:手机淘宝卖家推荐 编辑:程序博客网 时间:2024/05/17 07:47
在多数情况下,C++将数组名视为数组的第一个元素的地址;一种例外情况是,将sizeof操作符用于数组名时,此时将返回整个数组的长度
(单位为字节)。如:
double wages[3];
double *pw = wages;
size of wages array = 24
size of pw pointer = 4


C++允许将指针和整数相加,加1的结果等于原来的地址值加上指向的对象占用的总字节数;还可以将一个指针减去另一个指针,获得两个
指针的差。后一种运算将得到一个整数,仅当两个指针指向同一个数组时,这种运算才有意义;这将得到两个元素的间隔。
int tacos[10] = {5,2,8,4,1,2,2,4,6,8};
int *pt = tacos;        //suppose pt and tacos are the address 3000;
pt = pt + 1;            //now pt is 3004 if an int is 4 bytes;
int *pe = &tacos[9];    //pe is 3036 if an int is 4 bytes;
pe = pe - 1;            //now pe is 3032,the address of tacos[8];
int diff = pe - pt;     //the diff is 7,the seperation between tacos[8] and tacos[1].


使用方括号数组表示法等同于对指针解除引用:
tacos[0] means *tacos means the value at address tacos
tacos[3] means *(tacos+3) means the value at address tacos+3
数组名和指针变量都是如此,因此对于指针和数组名,既可以使用指针表示法,也可以使用数组表示法
int *pt = new int[10];  //pt points to block of 10 ints
*pt = 5;                //set element number 0 to 5
pt[0] = 6;              //set element number 0 to 6
pt[9] = 44;             //set element number 9 to 44
int coats[10];
*(coats+4) = 12;        //set coats[4] to 12


多维数组,用户可以创建每个元素本身都是数组的数组。例如:
int maxtemps[4][5];
该声明意味着maxtemps是一个包含4个元素的数组,其中每个元素都是一个由5个整数组成的数组。可以将maxtemps数组看作由4行组成,其
中每一行有5个int值;可以认为第一个下标表示行,第二个下标表示列;
maxtemps
然后我们来理解
maxtemps+1              //+1原来的地址值加上指向的对象占用的总字节数,所指向的对象是由5个整数组成的数组,
                        //即表示第1行的首地址
maxtemps[1]             //maxtemps[1]是数组maxtemps的第二个(number 1)元素,因此它本身也是由5个int组成的数组,由文章的第一句
                        //话,可得知maxtemps[1]表示第1行第0列的地址;