Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I allocate 1D array by using pointer to pointer (int **)

What is the difference in

void AllocateArray(int **arr,int size)

and:

void AllocateArray(int *arr,int size)

I have to allocate only 1D array by using both, and what is difference?

like image 346
Shahid Sohail Avatar asked Aug 25 '26 10:08

Shahid Sohail


1 Answers

I suppose the usage should be:

int* arr;
AllocateArray(&arr, 10);
// array has been allocated, use arr[0]...arr[9].
// ...
delete[] arr;  // don't forget this

According to the function's name, it might allocate the memory for the array. Such as:

void AllocateArray(int **arr,int size) {
    *arr = new int[size];
}

The second AllocateArray's parameter(i.e. int *arr) is passed by value, that means even the memory is allocated inside the function, it has nothing to do with the outside variable.

like image 79
songyuanyao Avatar answered Aug 27 '26 00:08

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!