Note: This answer is relevant for the C tag only. In C++ it's different and also something you would seldom (like nearly never) do.
I want to know if **Arr - A pointer to a pointer can be used as a 2D array.
Yes, it's called jagged array. You do it like:
int rows = 2;
int cols = 2;
int** arr = malloc(rows * sizeof *arr);
for (int i=0; i<rows; ++i)
{
arr[i] = malloc(cols * sizeof *arr[i]);
}
Now you can access, e.g. arr[1][0]
When done with the array, you need to free it. It's the "reverse" operation of your malloc
. Like:
for (int i=0; i<rows; ++i)
{
free(arr[i]);
}
free(arr);
Another alternative is to use a pointer to an array of cols
int
. Like
int (*arr)[cols] = malloc(rows * sizeof *arr);
... use arr, e.g. arr[1][0] = 42; ...
free(arr);
The benefit of the second code is that it is much simpler (less code, fewer calls of malloc
and free
resulting in better performance).
Jagged arrays are good in cases where you need a variable number of columns in the rows. For instance if some rows only require 10 integers and other rows require 10.000 integers, you can save memory by only allocating the number of columns actually needed for the specific row (instead of always allocating the MAX number of columns for all rows). Further, it's good if you need to change the number of columns at runtime (using, e.g. realloc
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…