易百教程

83、C语言中双指针(指向指针的指针)有什么用?

C语言中有很多双指针的应用,但这里我描述的是双指针的一个重要应用。 如果想创建一个函数来分配内存,并且想从函数参数中取回分配的内存,那么需要在这种情况下使用双指针。 看下面的代码:

#include<stdio.h>
#include<stdlib.h>
void AllocateMemory(int **pGetMemory,int n)
{
    int *p = malloc(sizeof(int)*n);
    if(p == NULL)
    {
        *pGetMemory = NULL;
    }
    else
    {
        *pGetMemory = p;
    }
}
int main()
{
    int *arr = NULL;
    int len = 10;
    int i =0;
    //Allocate the memory
    AllocateMemory(&arr,len);
    if(arr == NULL)
    {
        printf("Failed to allocate the memory\n");
        return -1;
    }
    //Store the value
    for(i=0; i<len; i++)
    {
        arr[i] = i;
    }
    //print the value
    for(i=0; i<len; i++)
    {
        printf("arr[%d] = %d\n",i, arr[i]);
    }
    //free the memory
    free(arr);
    return 0;
}