×

C 数组与指针

96
RiverLi
2017.10.08 00:40* 字数 195

指针

例子1:

int a = 5;
int *p = &a;
std::cout << "a = " << a << "\n";
std::cout << "&a = " << &a << "\n";
std::cout << "p = " << p << "\n";
std::cout << "&p= " << &p << "\n";
std::cout << "*p= " << *p << "\n";

/*
//输出
a = 5
&a = 0x7fff5fbff63c
p = 0x7fff5fbff63c
&p= 0x7fff5fbff630
*p= 5
*/

//以下两句会报错
//Cannot take the address of an rvalue of type 'int *'
std::cout << "&&a = " << &(&a) << "\n";
std::cout << "&&p= " << &(&p) << "\n";

从例子1中可以看出:

    1. 指针是一个变量,其值为另一个变量的地址,即:内存位置的直接地址。
        2. p是一个指针变量,其值是变量a的地址。
        3. &是取地址符。
        4. \* 取回指针变量所指定地址的变量的值。

指针与一维数组

例子2:

int a[3] = {1, 2, 3}; 

std::cout << "a = " << a << "\n";
std::cout << "&a[0] = " << &a[0] << "\n";
std::cout << "a[0] = " << a[0] << "\n";
std::cout << "*a = " << *a << "\n";
/*
//输出
a   = 0x7fff5fbff62c
&a[0]   = 0x7fff5fbff62c
a[0] = 1
*a = 1
*/

int *p = a;
std::cout << "p = " << p << "\n";
std::cout << "*p = " << *p << "\n";
std::cout << "*(p+1) = " << *(p+1) << "\n";
std::cout << "*(p+2) = " << *(p+2) << "\n";

/*
//输出
p = 0x7fff5fbff62c
*p = 1
*(p+1) = 2
*(p+2) = 3
*/

从上面代码可以看出:

  1. 一维数组的变量名的值是该数组第一个元素的地址。

指针与二维数组

二维数组示意图
二维数组示意图
int a[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};
std::cout << "a = " << a << "\n";
std::cout << "a[0] = " << a[0] << "\n";
std::cout << "&a[0][0] = " << &a[0][0] << "\n";
std::cout << "a[0][0] = " << a[0][0] << "\n";

/*
a = 0x7fff5fbff600
a[0] = 0x7fff5fbff600
&a[0][0] = 0x7fff5fbff600
a[0][0] = 1
*/

std::cout << "sizeof(a) = " << sizeof(a) << "\n";
std::cout << "sizeof(a[0]) = " << sizeof(a[0]) << "\n";

/*
sizeof(a) = 48
sizeof(a[0]) = 16
*/

int (*p)[4] = a;
std::cout << "p = " << p << "\n";
std::cout << "p[0] = " << p[0] << "\n";
std::cout << "*p[0] = " << *p[0] << "\n";

//将二维转为一维
int *b = (int *)a;
std::cout << "b = " << b << "\n";
std::cout << "*b = " << *b << "\n";
std::cout << "*(b+1) = " << *(b+1) << "\n";
std::cout << "*(b+2) = " << *(b+2) << "\n";
//通过一维数组访问二维数组中的i行n列
*(b + i*rowCount + n);


//作为参数
// int *b = (int *)a;
// test(b, 3, 4);
void test(int *a, int row, int column);
// test(a, 3, 4);
void test(int a[][4], int row, int colum);
// 错误
void test(int **a, int row, int column);
  1. 在二维数组中,数组名a,a[0]的值都是第一个元素a[0][0]的地址。
  2. 二维数组在内存中也是按顺序排列的。
  3. 二维数组在C语言中是一维数组,且每个元素又指向一个一维数组。

demo

点击去下载

参考

理解lvalue和rvalue
指针变量、普通变量、内存和地址的全面对比
《C和指针》

交流群

移动开发交流群:264706196

C
Web note ad 1