0

I have two arrays array1 of size 3 and array2 of size 2. I wish to form a pair of each item from both arrays. That is;

int array1[] = {1, 2, 3};
int array2[] = {9, 4};

Results I'm hoping to achieve:
1 , 9
1 , 4
2 , 9
2 , 4
3 , 9
3 , 4

This is what I have tried:

#include <iostream>

using namespace std;

int main(int argc, const char *argv[])
{
    int array1[] = {1, 2, 3};
    int array2[] = {9, 4};

    int arrayOneSize = sizeof(array1);
    int arrayTwoSize = sizeof(array2);

    for (size_t i = 0; i < arrayOneSize; i++)
    {
        for (size_t j = 0; j < arrayTwoSize; j++)
        {
            cout << array1[i] << " , " << array2[j] << endl;
        }

    }

    return 0;
}

But for some reason I am getting a whole bunch of weird combinations like:
1,9
1,4
1,1
1,2
1,3
1,1029505037
1,-531587312
... (It's really long, just want to shorten the results a little)
0,-411331072
1,9
1,4
1,1
1,2
1,3
1,1029505037
1,-531587312
1,-411331072

Sorry for the noob question. I am still new to C++ so, I will gladly appreciate any help. And also why am I getting numbers which are not part of the array?

Thanks in advance.

2 Answers2

4

To get the number of elements in an array, you have to divide its size by the size of an element in it:

int arrayOneSize = sizeof(array1) / sizeof(array1[0]);
int arrayTwoSize = sizeof(array2) / sizeof(array2[0]);

As Jarod42 points out, you can use the range-based for loop for the arrays and bypass finding the size manually all-together.
Alternatively, consider using std::array, or better yet, std::vector. Here's an implementation with modern C++:

#include <iostream>
#include <vector>

int main() {
  std::vector vec1{ 1, 2, 3 };  // no need for <int> with C++17
  std::vector vec2{ 9, 4 };

  for (auto&& e1 : vec1) {
    for (auto&& e2 : vec2) {
      std::cout << e1 << " , " << e2
                << '\n';  // no need to flush the buffer all the time
    }
  }
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
2

The size ( no. of elements in each array) computation of arrays is having the issue.

int arrayOneSize = sizeof(array1);
int arrayTwoSize = sizeof(array2);

This will be number of elements * sizeof(int) which gives the total size. Since you are interested only in number of elements, you should rather do

int arrayOneSize = sizeof(array1)/sizeof(int);
int arrayTwoSize = sizeof(array2)/sizeof(int);

This should give the expected output

Wander3r
  • 1,801
  • 17
  • 27