在初始化函数数组 [英] Initialize array in function
本文介绍了在初始化函数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我想通过函数初始化一个指向数组的指针,我做以下内容:
When I want to initialize a pointer to an array through the function, I am doing the following:
初始化,并通过功能破坏阵:
Initialize and destroy array through functions:
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;
}
初始化指针数组:
Initialize pointer to array:
int *pArr;
int initStatus = initArr(&pArr);
if(initStatus == 0)
{
printf("%s", "error");
return 0;
}
与指针数组工作:
Working with pointer to array:
*pArr = 1;
*(pArr + 1) = 2;
printf("0 = %i\n", *pArr);
printf("1 = %i\n", *(pArr + 1));
销毁指针数组:
Destroy pointer to array:
destroyArr(pArr);
pArr = NULL;
这是正确的和安全的?
Is this correct and safe?
推荐答案
我没有测试它,但它似乎是正确的。 A小调评论,虽然:你不需要设置改编
或 B
到 NULL
,他们在其范围的尽头,不能(安全)之后访问的反正。
I haven't tested it, but it appears correct. A minor comment, though: you don't need to set arr
or b
to NULL
, they're at the very end of their scope and can't be (safely) accessed after that anyway.
这篇关于在初始化函数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文