-2

Starting with two arrays a and b, I am trying to output a matrix c with dimensions sizeof(a) and sizeof(b), whose entries are the product of every pair of the Cartesian product of a and b.

Theses products are also stored in a two dimensional array c.

My code is below.

#include <iostream>
#include <string>

int main()
{   
    int a[]= { 1,2,3,4,5,5 };
    int b[]= { 1,23,2,32,42,4 };
    int c[sizeof(a)][sizeof(b)];

    for (int i = 0; i < sizeof(a); i++) {
        for (int j = 0; j < sizeof(b); j++) {
            c[i][j] =  a[i]* b[j] ;
            std::cout << c[i][j] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

My output is:

1 23 2 32 42 4 -858993460 -858993460 1 2 3 4 5 5 -858993460 16710224 15543422 1 2161328 2122464 16710312 15543008 196436084 15536213
2 46 4 64 84 8 -1717986920 -1717986920 2 4 6 8 10 10 -1717986920 33420448 31086844 2 4322656 4244928 33420624 31086016 392872168 31072426
3 69 6 96 126 12 1717986916 1717986916 3 6 9 12 15 15 1717986916 50130672 46630266 3 6483984 6367392 50130936 46629024 589308252 46608639
...

This is just a small part of the output.

jww
  • 97,681
  • 90
  • 411
  • 885
ashgeo
  • 13
  • 1
  • When they say `sizeof` what they really mean is the number of elements in the array. – David G Jun 22 '19 at 18:33
  • 2
    Just print the value of `sizeof(a)` and you'll get what's going on – Sergey Krusch Jun 22 '19 at 18:36
  • @0x499602D2 sure thing you meant to say bytes, not elements, right? – Sergey Krusch Jun 22 '19 at 18:38
  • 1
    Possible duplicate of [ARRAYSIZE C++ macro: how does it work?](https://stackoverflow.com/q/4064134/608639), [Is there a standard function in C that would return the length of an array?](https://stackoverflow.com/q/1598773/608639), [Array-size macro that rejects pointers](https://stackoverflow.com/q/19452971/608639), etc. – jww Jun 22 '19 at 18:42

1 Answers1

4

sizeof(a) is not the length of the array, it is the number of bytes required to store it.

Since the element type of the array is larger than one byte each, the numbers are different.

Timbo
  • 27,472
  • 11
  • 50
  • 75