假设您有如下代码。
int x=10;
这里 x 是一个保存值 10 的变量。变量 x 只不过是某个内存地址的标签。
x
+-------+
| 10 | 4050 which is x
+-------+
所以值 10 存储在 4050 中。它总是很难记住内存地址。因此,您可以通过命名它并使用该名称来简化操作。这里的 x 只不过是内存地址 4050 的标签。
int *x_ptr;
这里x_ptr是一个指针变量,可以存储任意整型变量的内存地址。
+-------+
| GBV | 5000 which is x_ptr
+-------+
这里 x_ptr 是地址 5000 的标签。最初,该变量将包含垃圾值 (GBV)。
x_ptr = &x;
上述语句将 x 的地址存储在 x_ptr 中。
+-------+
| 4050 | 5000
+-------+
x_ptr = &x = 4050
printf("%u",x_ptr); // 4050
printf("%d", *x_ptr); // 10
*x_ptr = *(4050) = valueAt(4050) = 10
现在让我们讨论一下您的代码。
int *ptr;
+-------+
| GBV | 6000 which is ptr
+-------+
int array[4] = {1,2,3,4};
+-----------+
| 1 | 7824 which is array+0 or array[0]
+-----------+
| 2 | 7828 which is array+1 or array[1]
+-----------+
| 3 | 7832 which is array+2 or array[2]
+-----------+
| 4 | 7836 which is array+3 or array[3]
+-----------+
这里数组 = 7824
int *arrayEnd = array + n;
内存位置的增量将根据数据类型增加字节数。
array+0 = 7824 + 0 = 7824
array+1 = 7824 + 1(4 bytes in case of integer) = 7824 + 4 = 7828
when n=4
arrayEnd = 7824 + 16 = 7840
+-------+
| 7840 | 6010 which is arrayEnd
+-------+
for (ptr = array; ptr < arrayEnd; ++ptr)
sum += *ptr;
这里 ptr 用数组的基地址(7824)初始化。所以 7824 将存储在内存 6000 中。
6000 6000
+-------+ +-------+
| GBV | => | 7824 | 6000 which is ptr
+-------+ +-------+
所以现在ptr = 7824
For Loop
+-------+--------------+-------------+
| ptr | *ptr | sum + =*ptr | // 7824 < 7840
+-------+--------------+-------------+
| 7824 | *(7824) = 1 | sum += 1 | // 7828 < 7840
+-------+--------------+-------------+
| 7828 | *(7828) = 2 | sum += 2 | // 7832 < 7840
+-------+--------------+-------------+
| 7832 | *(7832) = 3 | sum += 3 | // 7836 < 7840
+-------+--------------+-------------+
| 7836 | *(7836) = 4 | sum += 4 | // 7840 !< 7840 so loop terminates
+-------+--------------+-------------+
为什么 ptr = array 而不是 *ptr = array?
valueAt(*) has to be used when you have to store some value in the memory address.
ptr= array; //initializing base address of array to ptr.
6000 6000
+-------+ +-------+
| GBV | => | 7824 | 6000 which is ptr
+-------+ +-------+
*ptr = array; // ptr already has a address pointed to, and you store array's base address inside that memory location.
6000
+-------+
| GBV | *ptr= *(GBV) = Unknown = array // No guarantee that GBV is a proper memory address
+-------+
如果 ptr 已经有一些正确的内存地址,比如 1000,那么就像
6000
+-------+
| 1000 | *ptr= *(1000) = valueAt(1000) = array
+-------+
which makes
1000
+-------+
| 7824 |
+-------+
带有多指针的简单示例。
#include<stdio.h>
int main()
{
int x=10;
int *y=&x;
int **z=&y;
printf("%d --> %d --> %d",x,*y,**z);
return 0;
}
OUTPUT:
10 --> 10 --> 10