-2

Below is some code that I am trying to write for my class. I have the dot product worked out. Cross product is giving me some trouble. Having trouble understanding the error I get:

invalid conversion from 'int*' to 'int'

#include <iostream>
#include <string>

using namespace std;


int A[3];
int B[3];
int length = 3;
int cross[3];

int dotProduct (int A[], int B[]){
  int product = 0;
  for (int i = 0; i < length; i++)
    {
      product = product + A[i] * B[i];
    }
  return product;
}

int crossProduct(int A[], int B[], int cross[]){
    cross[0]=A[1] * B[2]-A[2] * B[1];
    cross[1]=A[2] * B[0]-A[0] * B[2];
    cross[2]=A[0] * B[1]-A[1] * B[0];
    return cross;
}

int main (){
  cout << "Please enter the coordinates for vector A: " << endl;
  cout << "X: ";
  cin >> A[0];
  cout << endl << "Y: ";
  cin >> A[1];
  cout << endl << "Z: ";
  cin >> A[2];
  cout << endl;

  cout << "Please enter the coordinates for vector B: " << endl;
  cout << "X: ";
  cin >> B[0];
  cout << endl << "Y: ";
  cin >> B[1];
  cout << endl << "Z: ";
  cin >> B[2];
  cout << endl;

  cout << "Dot Product is: " << dotProduct (A, B) << endl;
  crossProduct (A, B, cross);
  cout << "Cross Product is: ";
  for (int i=0;i<length;i++){
      cout << crossProduct[i]<<" ";
  }

  return 0;
}
O'Neil
  • 3,790
  • 4
  • 16
  • 30
  • If you're returning an `int`, you need to return a single `int`. An array of `int` is not an `int`. Also, a little secret: `cout << "Dot Product is: " << std::inner_product(A, A + 3, B, 0);` See [here](https://en.cppreference.com/w/cpp/algorithm/inner_product) – PaulMcKenzie Sep 27 '18 at 23:33
  • `cross` is global. There is no need to return anything from `crossProduct`. Whether this is a good idea or not... That would be another question. – user4581301 Sep 27 '18 at 23:33
  • 1
    Unrelated: `cout << crossProduct[i]<<" ";` looks a bit goofy. I think you mean `cout << cross[i]<<" ";`. Right now you're trying to use a function as an array. – user4581301 Sep 27 '18 at 23:35
  • 1
    `cross` is also passed into `crossProduct`. Reusing a name like this can lead to confusing code. [Read up on Variable Shadowing.](https://en.wikipedia.org/wiki/Variable_shadowing) – user4581301 Sep 27 '18 at 23:38
  • Handy reading: [Are global variables bad?](https://stackoverflow.com/questions/484635/are-global-variables-bad) – user4581301 Sep 27 '18 at 23:40

1 Answers1

0

For the dot product, I would write:

int
dotProduct(const int A[], const int B[])
{
  return std::inner_product(A, A + length, B, 0);
}

For the cross product, you should rather write:

...
  crossProduct (A, B, cross);
  cout << "Cross Product is: ";
  for (int i=0;i<length;i++){
      cout << cross[i]<<" ";
  }
...