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;
}
For starters variable length arrays like this
is not a standard C++ feature. Instead use the standard container
std::vector
.This while loop
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
has the return type
int
but returns nothing.In this assignment statement
the left operand has the type
int[n]
while the return type of the functionint
. 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
tovoid
and remove the assignment statement.Also you should use the standard C function
srand
to get different sequences of random numbers.