Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

c++ - Can double pointers be used as 2D arrays

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...