指向指针的指针在 C 中如何工作?
首先,指针是一个变量,与任何其他变量一样,但它保存变量的地址。
指向指针的指针是一个变量,与任何其他变量一样,但它保存变量的地址。该变量恰好是一个指针。
您什么时候使用它们?
当您需要返回指向堆上某些内存的指针时可以使用它们,但不使用返回值。
例子:
int getValueOf5(int *p)
{
*p = 5;
return 1;//success
}
int get1024HeapMemory(int **p)
{
*p = malloc(1024);
if(*p == 0)
return -1;//error
else
return 0;//success
}
你这样称呼它:
int x;
getValueOf5(&x);//I want to fill the int varaible, so I pass it's address in
//At this point x holds 5
int *p;
get1024HeapMemory(&p);//I want to fill the int* variable, so I pass it's address in
//At this point p holds a memory address where 1024 bytes of memory is allocated on the heap
还有其他用途,例如每个 C 程序的 main() 参数都有一个指向 argv 指针的指针,其中每个元素都包含一个字符数组,这些字符是命令行选项。您必须小心,但当您使用指针的指针指向二维数组时,最好使用指向二维数组的指针。
为什么它很危险?
void test()
{
double **a;
int i1 = sizeof(a[0]);//i1 == 4 == sizeof(double*)
double matrix[ROWS][COLUMNS];
int i2 = sizeof(matrix[0]);//i2 == 240 == COLUMNS * sizeof(double)
}
这是一个正确完成的指向二维数组的指针示例:
int (*myPointerTo2DimArray)[ROWS][COLUMNS]
如果您想为 ROWS 和 COLUMNS 支持可变数量的元素,则不能使用指向二维数组的指针。但是,如果您事先知道,您将使用二维数组。