Problem with c++ function - error: incompatible types in assignment of ‘int’ to ‘int [n]’

1.9k Views Asked by At

i want to make function in c++ called 'losowanie', this function should random n numbers between 0-n. When i call this function, then i get :

error: incompatible types in assignment of ‘int’ to ‘int [n]’

Here is my code :

 #include <iostream>
    #include <stdlib.h>
    #include <time.h>
   
using namespace std;

int losowanie (int tab[], int n) {
    for(int i = 0;i<n; i++) {
        tab[i] = rand() % n + 1;
        cout<<tab[i]<<endl;
    }
}

int main()
{
    int n = -1;
    
    while(n<0 || n>50) {
        cout<<"Give number (  0 - 50)"<<endl;
        cin>>n;
    }
    
    int tab[n];
    tab = losowanie(tab, n); //here is error
    
    return true;
}
2

There are 2 best solutions below

0
On

For starters variable length arrays like this

int tab[n];

is not a standard C++ feature. Instead use the standard container std::vector.

This while loop

while(n<0 || n>50) {

allows to enter the value 0 for the variable n. However you may not declare a variable length array with 0 elements.

The function losowanie

int losowanie (int tab[], int n) {
    for(int i = 0;i<n; i++) {
        tab[i] = rand() % n + 1;
        cout<<tab[i]<<endl;
    }
}

has the return type int but returns nothing.

In this assignment statement

tab = losowanie(tab, n);

the left operand has the type int[n] while the return type of the function int. So the compiler issues an error because this statement does not make a sense. Arrays do not have the assignment operator.

You could change the type of the function from int to void and remove the assignment statement.

Also you should use the standard C function srand to get different sequences of random numbers.

0
On

losowanie returns int, but tab is an array. It is enough to make losowanie to a void function.

void losowanie (int tab[], int n) {
for(int i = 0;i<n; i++) {
    tab[i] = rand() % n + 1;
    cout<<tab[i]<<endl;
}

And, in main:

int tab[n];
losowanie(tab, n);