Reputation: 21
Suppose I have a 2D array - int Array[2][2]; I know that I can implement an array having 4 elements with 2 in each row [1 row makes an array]. I want to know if **Arr - A pointer to a pointer can be used as a 2D array.
Upvotes: 2
Views: 421
Reputation: 1409
Yes, it can be used. As there is already an answer, which explicitly mentions that It is for C.
You can use create a two-indirection array in C++.
int size = 5;
int** array = new int*[size]; // Array of pointers to array of ints
for (int i = 0; i < size;++i){
array[i] = new int[size];
}
Do not forget to free the memory with the delete []
operator.
for(int i = 0; i < size; ++i){
delete [] array[i];
}
delete[] array;
If you are using C++, you will probably never use this, you should consider using vector
or array
as they make your code more verbose, and manage the memory themselves. And more cache-friendly.
Upvotes: 0
Reputation: 44274
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
).
Upvotes: 6