我正在尝试使用指针算法来访问像数组这样的指针位置。为了测试相同,我写了下面的代码。
现在,我可以看到指针算法正在工作,因为我可以看到递增的指针地址被打印出来。但是,当我取消引用该指针位置以设置某个值时,它就不起作用了。
到目前为止,根据我对 C 和指针的了解,我无法解释为什么指针取消引用不起作用。如果我无法获得增加的指针位置/地址,那么至少我会理解指针算法不起作用,但是当它起作用时,为什么指针取消引用不起作用。
代码:
#include<stdio.h>
#include<stdlib.h>
int **DoublePtr;
void doublePointerTest();
int main(void)
{
doublePointerTest();
}
void doublePointerTest()
{
DoublePtr = malloc(sizeof(int*));
*DoublePtr = malloc(sizeof(int) * 10);
printf("Address of DoublePtr = %p\n", DoublePtr);
printf("Address of *DoublePtr = %p\n", *DoublePtr);
**DoublePtr = 100;
*DoublePtr += 1;
printf("+1 Address of *DoublePtr = %p\n", *DoublePtr);
**DoublePtr = 1;
*(*DoublePtr += 1) = 2;
printf("+2 Address of *DoublePtr = %p\n", *DoublePtr);
//**DoublePtr = 2;
*DoublePtr += 1;
printf("+3 Address of *DoublePtr = %p\n", *DoublePtr);
**DoublePtr = 3;
// *DoublePtr[4] = 4;
// *DoublePtr[8] = 8;
// *DoublePtr[3] = 3;
// *DoublePtr[2] = 2;
for(int i = 0; i < 10; i++, *DoublePtr += 1)
{
printf("%d. ", i);
printf("%d\n", **DoublePtr);
}
}
输出/输出:
jharvard@appliance (~/psets/pset5/pset5_working): clang testing.c -o testing
jharvard@appliance (~/psets/pset5/pset5_working): ./testing
Address of DoublePtr = 0x8cd4008
Address of *DoublePtr = 0x8cd4018
+1 Address of *DoublePtr = 0x8cd401c
+2 Address of *DoublePtr = 0x8cd4020
+3 Address of *DoublePtr = 0x8cd4024
0. 3
1. 0
2. 0
3. 0
4. 0
5. 0
6. 0
7. 0
8. 135105
9. 0
jharvard@appliance (~/psets/pset5/pset5_working):
更新:
根据评论和答案,将我的代码从DoublePtr = malloc(sizeof(int));
to更正DoublePtr = malloc(sizeof(int*));
并进行了测试,但它给出了相同的结果。