combining numerical arrays with pointers

Hi there,

I'm in the process of teaching myself C++ with several books including "Sams...C++ in 21 Days". In the Q&A section of Chapter (Day) 13 of the Sams book ("Managing Arrays and Strings") the authors state that "with simple arrays, you can use pointers to combine them into a new, larger array."

I take this to mean that it is possible to combine numerical arrays (as opposed to strings, where the strcat method can be used).

But I'm unable to locate any specific mention of how to do this in any of my books or online.

This is the code I've started with (which compiles and runs but only gives me access to arrayOne's data through arrayThree):

// combining arrays with pointers
#include <iostream>
using namespace std;

int main()
{
int arrayOne[3]={1,3,5};
int arrayTwo[3]={2,4,6};
int *arrayThree=new int[6];
arrayThree=arrayOne;
cout << arrayThree[2] << endl;
delete[] arrayThree;
return 0;
}

I wonder if anyone have an insight into this question. Thanks for any help you might be able to provide.

Last edited on
I haven't read Sam's series books... but there are two ways to combine arrays:

Concatenation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;

#define LEN( a ) (sizeof( a ) / sizeof( a[ 0 ] ))

int main()
  {
  int odd[]  = { 1, 3, 5 };
  int even[] = { 2, 4, 6 };

  int* all = new int[ LEN( odd ) +LEN( even ) ];

  #if 0
    // This uses the stuff in <string>

    char_traits <int> ::copy( all,             odd,  LEN( odd  ) );
    char_traits <int> ::copy( all +LEN( odd ), even, LEN( even ) );

  #else
    // This uses the stuff in <algorithm>

    copy( odd,  odd  +LEN( odd  ), all             );
    copy( even, even +LEN( even ), all +LEN( odd ) );

  #endif

  // Here's more <algorithm> stuff, along with <iterator>
  copy( 
    all, 
    all +LEN( odd ) +LEN( even ),
    ostream_iterator <int> ( cout, " " )
    );
  cout << endl;

  delete[] all;
  return 0;
  }


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

int main()
  {
  int odd[]  = { 1, 3, 5 };
  int even[] = { 2, 4, 6 };

  int* all[ 2 ] = { odd, even };

  // Here's a simple way of doing it... ;-)
  for (unsigned j = 0; j < 3; ++j)
    {
    for (unsigned i = 0; i < 2; i++)
      cout << all[ i ][ j ] << " ";
    cout << endl;
    }

  return 0;
  }


Hope this helps.
Thanks so much for your help; I really appreciate it.

I'll have to spend some time with your first example but I was interested to learn (by your second example) that array elements need to be initialized again when they're re-assigned to a new array (on the heap).
Topic archived. No new replies allowed.