可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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.
回答2:
The initArr function can be reduced to:
int initArr(int **b) { *b = malloc(2 * sizeof **b); return *b ? 1 : 0; }
回答3:
In fact, initArr and destroyArr do not add any value at all. They wrap the standard C functions to return and do the exact same thing.
Also, you could use array indexers [] to access individual members of the allocated array.
Here is a working equivalent:
int* pArr = (int*) malloc(2 * sizeof(int)); if (pArr) { pArr[0] = 1; pArr[1] = 2; printf("0 = %d\n", pArr[0]); printf("1 = %d\n", pArr[1]); free(pArr); }
回答4:
Looks good but the free
in destroyArr()
does not give you anything since you are not passing a double pointer to it.