3

有什么区别

void AllocateArray(int **arr,int size)

和:

void AllocateArray(int *arr,int size)

我必须同时使用两者来分配一维数组,有什么区别?

4

2 回答 2

2

我想用法应该是:

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

根据函数的名称,它可能会为数组分配内存。如:

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

第二个AllocateArray参数(即int *arr)是按值传递的,这意味着即使内存是在函数内部分配的,它与外部变量无关。

于 2016-02-11T08:52:30.673 回答
1

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

int **p=new int*[1];
*p=new int[20];

But why? It is too bad to do it like this

What is the difference

void AllocateArray(int **arr,int size) can change the address of the array not just the content of it. In other words:

int *p;
AllocateArray(&p,5);

Will be able to change where p is pointing to.

void AllocateArray(int *arr,int size) can only change the content of the array. In other words:

int *p;
AllocateArray(p,5);

Will be change the content of p without changing where it is pointing to.

P.S. I know that pointer != array but since it is an elementary question I did not need to dig into such detail for the OP.

Final Note:

Please use std::vector instead all of these pointers. You will be in peace and feel loved.

于 2016-02-11T08:54:34.507 回答