3

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?

3
  • I see no flaw in your approach. Good work. Commented Jun 3, 2012 at 13:59
  • 2
    Most people find pArr[1] = 2; easier to read than your *(pArr + 1) = 2;. They are equivalent. Commented Jun 3, 2012 at 14:03
  • In C, usually success is indicated by 0, and non-zero is a kind of failure. The call to malloc will return NULL or a valid address, but standard fare is the function that does that would normally return 0 for success. Commented Jun 3, 2012 at 21:58

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

The initArr function can be reduced to:

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

    return *b ? 1 : 0;
}

Comments

2

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);
}

Comments

-1

Looks good but the free in destroyArr() does not give you anything since you are not passing a double pointer to it.

1 Comment

Actually it does. Setting it to NULL doesn't affect the variable in the calling function but b does point to the memory intended to be freed and so frees it properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.