1

I was trying to write an algorithm that would take 2 numbers as input and output them in ascending order using the ternary operator, but on line 20:24 it tells me:

error: invalid array assignment

Can someone help me?

#include <iostream>

using namespace std;

int main()
{
     int a, b;
     int c[2];
     int d[2];
     int e[2];
     cout << "inserire il primo numero: ";
     cin >> a;
     cout << "inserire il secondo numero: ";
     cin >> b;

     c[0] = b;
     c[1] = a;
     d[0] = a;
     d[1] = b;
     e = (a > b) ? c : d;
     cout << e;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Marco Cracco
  • 7
  • 1
  • 2
  • 1
    This has nothing to do with ternary operator, C-style arrays are not assignable. `e = c;` would fail just the same. You can use `std::array c;` (same for `d` and `e`) and it would work. – Yksisarvinen May 15 '22 at 10:07
  • You cannot assign an array to something else. Perhaps you want `e` to be a pointer instead? Though even then the line `cout << e;` won't do what you probably expect it to – UnholySheep May 15 '22 at 10:07

2 Answers2

1

as long as the left side has the appropriate = operator, you can write this statement. C-Style arrays do not have this as you try to change their pointer. read more.

you can use std::array<int, 2>, which has the operator= and offers many benefits (read more):

#include <iostream>
#include <array>

int main() {
    int a, b;
    std::array<int, 2> c;
    std::array<int, 2> d;
    std::array<int, 2> e;

    std::cout << "inserire il primo numero: ";
    std::cin >> a;
    std::cout << "inserire il secondo numero: ";
    std::cin >> b;

    c = { b, a };
    d = { a, b };

    e = (a > b) ? c : d;

    for (auto& i : e) {
        std::cout << i << ' ';
    }
}

read here why you shouldn't use namespace std;.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
-1

Ternay operator works fine. In your code, the problem was in assigning the array. You can't assign an array like that.

One of the ways you can follow:

#include <iostream>

using namespace std;

int main()
{
     int a, b;
     int c[2];
     int d[2];
     int e[2];
     cout << "inserire il primo numero: ";
     cin >> a;
     cout << "inserire il secondo numero: ";
     cin >> b;

     c[0] = b;
     c[1] = a;
     d[0] = a;
     d[1] = b;
     (a > b) ? memcpy(e, c, sizeof c) : memcpy(e, d, sizeof d);

     cout << e[0] << " " << e[1] << endl;
}

Please check the below URL to learn more ways for assigning one array to another other than running a loop.

How to assign values of array to another array(making copy)

Md. Faisal Habib
  • 1,014
  • 1
  • 6
  • 14