0

Here is something that I've done in Java, but I am having difficulty figuring it out in C++.

Basically, I have two arrays, and I would like to copy the contents of the second array into the first array. Instead of wasting time in a loop that copies the contents of each array element one at a time from the second array to the first, I would just like my first array variable to point to the location where the second array is stored.

Here is an example:

void modify(int[]);

int main (){
  // foo points to (for example) memory location 123
  int foo[5] = { 16, 2, 77, 40, 12071 };

  modify(foo);
  // foo now contains the modified data

  return 0;
}

void modify(int bar[]){
// bar points to memory location 123
// (ie, bar points to the same location as foo)

  // baz points to (for example) memory location 4567
  int baz[5];

  // this loop can't modify my data in-place,
  // so it uses baz temporarily
  for(int i = 0; i < 5; i++){
    int j;
    if(i == 0) j = 4;
    else j = i - 1;
    baz[i] = bar[i] + bar[j];
  }
  // baz now contains the modified data

  // now, I would like to put the data located in 4567 (baz) into foo
  // I know I could loop through each element one at a time like:
  // for(int i; i < 5; i++)
  //   bar[i] = baz[i];
  // but I feel that for large arrays, this could be unnecessarily slow
  // it would be more efficient to say:
  // "ok, now foo points to memory location 4567"
  // but I don't know how to say that in C++
  bar = baz; // this doesn't work :-(
  foo = baz; // neither does this :'(
}

How would I do this in C++?

-- Brian

5
  • Use an std::vector instead of C-style arrays. The = operator will work then. You'll also be able efficiently swap the contents of two vectors. Commented Sep 22, 2014 at 21:15
  • 1
    You're talking about two entirely different things. Do you want to copy the contents of one array into another, or do you want two variables that both point to the same array? Commented Sep 22, 2014 at 21:16
  • Look up for std::copy(), std::vector<int> respectively. Commented Sep 22, 2014 at 21:16
  • After the modify() function returns, I only need a single array, foo[] which contains the new, modified data. Commented Sep 23, 2014 at 15:15
  • This is for the first project in my C++ class. We haven't touched OOP yet, so the use of objects or any other OOP stuff is off the table for this first project. Commented Sep 23, 2014 at 15:18

4 Answers 4

2

Use a std::vector.

You can use its swap member function but that’s only necessary for C-style code where you pass the argument by reference (or pointer).

Instead simply return the locally created result vector, and its buffer will be automatically moved into the function result.

#include <vector>
using namespace std;

auto modified( vector<int> const& v )
    -> vector<int>
{
    int const n = v.size();
    vector<int> result( n );
    for( int i = 0; i < n; ++i )
    {
        int const j = (i == 0? n - 1 : i - 1);
        result[i] = v[i] + v[j];
    }
    return result;
}

auto main()
    -> int
{
    vector<int> const   foo = { 16, 2, 77, 40, 12071 };
    vector<int> const   baz = modified( foo );
}

It’s in a way much like cooking.

The less you intervene, the more you let the compiler do its job, the generally better result with less effort.

Sign up to request clarification or add additional context in comments.

7 Comments

But what's the point of auto modified() -> vector<int>? vector<int> modified() is easier to understand, and shorter too.
@TonyK: what's the point of using two different syntaxes for function declarations?
It's easier on the eyes, for one.
@TonyK: on the contrary, the old syntax engages the eyes in violent acrobatics to find the function names. just start reading the Holy Standard if you don't believe it.
So why didn't you write auto result = vector<int> (n);?
|
0

In C++ you can't swap concretes arrays. What you can do is to use std::vector instead, and in particular use the std::vector::swap member function to swap them like in the example below:

#include <iostream>
#include <vector>

void modify(std::vector<int> &v);

int main () {
  std::vector<int> foo {16, 2, 77, 40, 12071};

  modify(foo);

  for(auto i : foo) std::cout << i << " ";
  std::cout << std::endl;

  return 0;
}

void modify(std::vector<int> &bar) {
  // baz points to (for example) memory location 4567
  std::vector<int> baz(bar.size());

  // this loop can't modify my data in-place,
  // so it uses baz temporarily
  for(int i(0), sz(bar.size()); i < sz; ++i){
    int j;
    if(i == 0) j = 4;
    else j = i - 1;
    baz[i] = bar[i] + bar[j];
  }
  bar.swap(baz);
}

LIVE DEMO

Comments

0

In C++, arrays don't point. It's not possible to make an array "point" somewhere, nor is it possible for two arrays to share memory space. Only pointers point.

Further, baz is an automatic variable within modify. It is destroyed when modify finishes, so it would be a bad idea to return a pointer pointing to baz.

To do what you are describing requires the caller and callee to both agree on a memory allocation technique (since the callee has to allocate new memory and then free the old memory when done). It's almost certainly slower to do a memory allocation and free than it is to copy 5 ints.

If you really want to do that then the thing to do is use vector instead of an array (this wraps a dynamic allocation); pass it by reference to your function, and in the function have another vector and then when you're done, do swap which will exchange contents of the two vectors in constant time.

Comments

0

If you just want to assign your array to new variable you can make a pointer. Pointer is a variable which stores the address of another variable. So you can simply make:

int bar[3] = {1, 2, 3};
int* baz = bar;

And this will work.

But you woun't be able to address new array to a static one. You should try creating a dynamic array like this:

int* foo = new int[3];

Now if you want your variable foo to point to another array you must delete the existing one:

delete []foo;
foo = baz;

(It will work without deleting it, but you will have a memory leak since there is no garbage collector)

P.S.

Here is more on pointers

Here is more on dynamic memory

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.