gpt4 book ai didi

c - 在函数中初始化数组

转载 作者:太空狗 更新时间:2023-10-29 15:59:16 25 4
gpt4 key购买 nike

当我想通过函数初始化一个指向数组的指针时,我正在做以下事情:

通过函数初始化和销毁​​数组:

int initArr(int **b)
{
int *arr = (int *) malloc(sizeof(int)*2);

if(arr == NULL)
return 0;

*b = arr;
arr = NULL;
return 1;
}

void destroyArr(int *b)
{
free(b);
b = NULL;
}

初始化指向数组的指针:

int *pArr;
int initStatus = initArr(&pArr);

if(initStatus == 0)
{
printf("%s", "error");
return 0;
}

使用指向数组的指针:

*pArr = 1;
*(pArr + 1) = 2;

printf("0 = %i\n", *pArr);
printf("1 = %i\n", *(pArr + 1));

销毁指向数组的指针:

destroyArr(pArr);
pArr = NULL;

这是正确和安全的吗?

最佳答案

我还没有测试过,但它看起来是正确的。不过,有一点要注意:您不需要将 arrb 设置为 NULL,它们位于作用域的最末端之后无论如何都不能(安全地)访问。

关于c - 在函数中初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10870891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com