How can you set the address of elements in an array to point to specific elements in another array?

StackOverflow https://stackoverflow.com/questions/21085578

  •  27-09-2022
  •  | 
  •  

Let's say we have an array with 10 elements and we want to extract a 6-element sub-array from it that contains the first three items and the last three items. I don't want the extracted sub-array to be an independent array but I want its items to point to the same locations in memory as the corresponding items in the original array. How can I do that?

有帮助吗?

解决方案

You can use an array of pointers to point to the elements in the other one:

int a[10] = { 5, 3, 7, 4, 9, 2, 0, 3, 3, 6 };
int* b[6];
b[0] = &a[0];
b[1] = &a[1];

and so on. You have to be sure that a lives t least as long as b.

A more idiomatic solution might be to use a range type to hold a pointer to the first and one past the last elements of interest. The range would be iterable in the same way as a standard library container. See boost.range for example, or you can roll out a minimal and simple version using pointers as iterators. This would satisfy your use-case. For example:

struct range
{
  typedef const int* const_iterator;
  const_iterator begin() const {return begin_;}
  const_iterator end() const { return end_; }
  range(const int* begin, const int* end) : begin_(begin), end_(end) {}
  std::size_t size() const {return end_ - begin_ };
private:
  int* begin_;
  int* end_;
};

Then

int a[10] = { 5, 3, 7, 4, 9, 2, 0, 3, 3, 6 };
range b(&a[0], &a[3);
for (range::const_iterator i = b.begin(); i != b.end(); ++i)
  std::cout << *i << " ";
std::cout << std::endl;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top