Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array in function

Tags:

arrays

c

pointers

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?

like image 886
tikhop Avatar asked Jun 06 '26 18:06

tikhop


2 Answers

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.

like image 161
Kevin Avatar answered Jun 09 '26 08:06

Kevin


The initArr function can be reduced to:

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

    return *b ? 1 : 0;
}
like image 31
wildplasser Avatar answered Jun 09 '26 07:06

wildplasser