如何获得一个指向二维动态数组子数组的指针? [英] how to get a pointer to the subarray of a 2d dynamic array?

查看:69
本文介绍了如何获得一个指向二维动态数组子数组的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维动态数组:

I have a two-dimensional dynamic array:

int **p=new int*[d1];
for(size_t i=0;i!=d1;++i)
  p[i]=new int[d2];



现在我需要一个子数组,例如



Now I need a subarray of it, like

int **b=&p[1][1]


(当然这是不正确的)
然后我可以使用b来操作p的一个块,例如
b[0][0]=10p[1][1]=10相同,
b[2][3]=20p[3][4]=20相同.
问题是:
如何构造指向p的子数组的指针?
谢谢!


(Of course this is not correct)
Then I could operate a block of p using b, such as
b[0][0]=10 is the same as p[1][1]=10,
b[2][3]=20 is the same as p[3][4]=20.
The question is:
How to construct such a pointer to the subarray of p?
Thank you!

推荐答案

我认为您不能以简单的方式做到这一点,您可以:
  • 为(d1-1)整数指针分配内存并正确分配它们.
I think you cannot do it in a simple way, you''ve either to:
  • allocate memeory for the (d1-1) integer pointers and assign them properly.
  • 使用函数重新映射数组的索引.


它不能走... :)
您可以获得唯一的int*可以在一行(列)中导航.
但是您可以编写一个类来实现这种行为(结果):)
It can not go... :)
You can obtain the only int* to navigate at one row (column).
But you could write a class to implement such behavior (results) :)


谢谢大家!

我完成了CPallini的第一个技巧.尽管我期望没有为b分配内存,但我至少为b分配了内存.
Thank you all!

I finished it with CPallini''s first tip. Though I expected no memory allocation for b, I at least reduced a dimension when allocating memory for b.


这篇关于如何获得一个指向二维动态数组子数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆