Initialize array in function

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!