我认为值得在其他答案中添加对 c 中指针、数组和内存位置的快速解释。
首先,c 中的数组只是一块足以容纳数组中项目数的内存块(请参阅http://www.cplusplus.com/doc/tutorial/arrays/)
所以如果我们说
int[5] example;
example[0] = 1;
example[1] = 2;
example[2] = 3;
example[3] = 4;
example[4] = 5;
假设 int 是 32 位,我们将有一个 5*32 位 = 160 位长的内存块。由于 C 是一种低级语言,它试图尽可能高效,因此尽可能少地存储有关数组的信息,在这种情况下,尽可能少的信息是第一个元素的内存地址。所以例子的类型可以表示为
int *example;
或者 example 指向一个 int。要获取数组中的项目,然后将正确的数字添加到示例中存储的地址并读取该内存地址处的数字。如果我们假设内存看起来像
Memory Address = Value (ints take up 4 bytes of space)
1000 = 1 <-- example
1004 = 2
1008 = 3
1012 = 4
1016 = 5
所以
int i = example[3]; //The 4th element
可以表示为
int i = *(example + 3 * sizeof(int));
int i = *(example + 3 * 4);
int i = *(1000 + 12);
int i = *(1012); // Fetch the value at memory location 1012
int i = 4;
sizeof(int) 为 4(int 为 32 位,或 4 * 8 位字节)。如果您尝试添加,则需要一个 8 位或 1 * 8 位字节的字符。
所以回到你的代码
char* p; // declare p as a pointer to a char/
p = (char *)a; // point p at memory location 3000
// p[b] would be the 21st element of the "array" p =>
// p[20] =>
// p + 20 * sizeof(char) =>
// p + 20 * 1 =>
// p + 20 =>
// 3000 + 20 =>
// 3020
// the & operator in c gets the address of the variable so
sum = (int) &p[b];
// &p[b] => find the address pointed to by p[b] => 3020
// (int) casts this pointer to a int.
所以 sum 被分配了数组第 21 个元素的地址。
冗长的解释。