Adding Arrays

I have two arrays: array1 and array2. I would like array1 to equal array1 plus array2. Below is the code I have so far, but I know I am really off.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int concat(int* array1, int array1Size, int* array2, int array2SIZE)
{
	int* array1 += new int[array2Size];
	for(int i = 0; i < array1; i++)
	{
		array[i] = array2;
	}
	return array;
}

int main()
{
	const int array1Size = 3;
	const int array2Size = 5;
	int* array1 = concat(array1, array1Size, array2, array2Size);
	for(int i = 0; i < SIZE; i++)
	{
		cout << array1[i] << endl;
	}
}


Please advise, thank you!
Last edited on
I have two arrays: array1 and array2.
1
2
3
4
5
6
int main()
{
  const int array1Size = 3;
  const int array2Size = 5;
  int* array1 = concat(array1, array1Size, array2, array2Size); // error
  // names 'array1' and 'array2' are not known 

You are right that most lines of your code do contain errors.

Lets try something different first:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> foo {2,4,8};
  std::vector<int> bar {1,3,7,9};

  // copy elements of bar to the end of foo

  for ( auto e : foo ) {
    std::cout << ' ' << e;
  }
  std::cout << '\n';
  return 0;
}

How would you implement line 9 now?
Hint: http://www.cplusplus.com/reference/vector/vector/insert/


The page in hint and several other pages about std::vector do mention reallocation that requires moving/copying elements. What happens in reallocation is that
1. a new block of memory is allocated
2. content is moved from old memory block to new block
3. old block is deallocated
4. the new block becomes the "current" block


Another exercise for you. Please show, how do you copy elements between arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>

int main()
{
  constexr size_t fooSize {7};
  int foo[fooSize] {2,4,8};
  constexr size_t barSize {4};
  int bar [] {1,3,7,9};

  // copy the four elements of bar to last four elements of foo

  for ( auto e : foo ) {
    std::cout << ' ' << e;
  }
  std::cout << '\n';
  return 0;
}
Thank you so much, that really helped!
Topic archived. No new replies allowed.