c语言二级指针的使用,malloc内存申请

2020-09-08 09:54:36 浏览数 (2)

代码语言:javascript复制
#include<stdio.h>
#include<stdlib.h>


void AllocateMemory(int **pGetMemory, int n)
{

    int *p = (int*)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 memoryn");
        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] = %dn", i, arr[i]);
    }

    //free the memory
    free(arr);


    return 0;

}

输入结果如下:

0 人点赞