首页 > 代码库 > 数组和指针
数组和指针
一、对于一维数组,指针和数组的行为是很像的。
#include <iostream>void TestOneDim(){ int a[] = {1,2,3,4,5}; char b[] = "abcdef"; int* ap = a; char* bp = b; std::cout << "ap : " << ap << std::endl; std::cout << "a : " << a << std::endl; std::cout << "bp : " << bp << std::endl; std::cout << "b : " << b << std::endl; std::cout << "ap[0] : " << ap[0] << std::endl; std::cout << "a[0] : " << a[0] << std::endl; std::cout << "bp[0] : " << bp[0] << std::endl; std::cout << "b[0] : " << b[0] << std::endl;}int main(){ TestOneDim();}
其输出结果为:
ap : 002EF718a : 002EF718bp : abcdefb : abcdefap[0] : 1a[0] : 1bp[0] : ab[0] : a
从结果看,一维数组和指针的行为是一致的。
二、对于二维数组,情况和一维数组有些不一样,比如二维数组不能直接赋给指针的指针;如果想用指针指向二维数组,需将数组赋给一个指向数组的指针,同时,如果想把二维数组赋给指针的指针,可以将二维数组赋给一个数组指针,再把数组指针赋给指针的指针就可以了。代码如下:
#include <iostream>void TestTwoDim();int main(){ TestTwoDim();}void TestTwoDim(){ int a[][3] = {1,2,3,4,5}; int* b[] = {a[0], a[1]}; int(* ap)[3] = a; int** bp = b; std::cout << "ap : " << ap << std::endl; std::cout << "ap[0] : " << ap[0] << std::endl; std::cout << "ap[0][0] : " << ap[0][0] << std::endl; std::cout << "----------------" << std::endl;
std::cout << "bp : " << bp << std::endl;
std::cout << "bp[0] : " << bp[0] << std::endl;
std::cout << "bp[0][0] : " << bp[0][0] << std::endl;
std::cout << "----------------" << std::endl;
std::cout << "a : " << a << std::endl;
std::cout << "a[0] : " << a[0] << std::endl;
std::cout << "a[0][0] : " << a[0][0] << std::endl;
}
输出结果为:
ap : 0042FA1C
ap[0] : 0042FA1C
ap[0][0] : 1
----------------
bp : 0042FA0C
bp[0] : 0042FA1C
bp[0][0] : 1
----------------
a : 0042FA1C
a[0] : 0042FA1C
a[0][0] : 1
从结果看,指向数组的指针和二维数组的行为是一致的,指针的指针和二维数组的行为不完全一致,不过在取值上已经是一样了。
数组和指针