Reputation: 23
what is the method to return an array to main? I know the array is created but cant return it, so when I try to use it is says "incompatible types in assignment"?
int* get_array(){
int i = 0, j;
int *array = malloc(6);
srand(time(NULL));
while (i != 6)
{
int random_number = ((rand() % 49) + 1);
int ok = 1;
for (j = 0 ; ok && j != i ; j++)
{
ok &= (random_number != array[j]);
}
if (ok)
{
array[i++] = random_number;
}
}
return array;
}
then call it from the main:-
int main()
{
int i;
int* get_lotto_numbers();
int numbers[6];
numbers = get_lotto_numbers();
for(i = 0; i < 6; i++)
{
printf("%d ", numbers[i]);
}
}
any comments will help thanks.
Upvotes: 0
Views: 143
Reputation: 2220
This should probably work for you.....
int* get_array(){
int i = 0, j;
int *array = malloc(6);
/*do your stuff here*/
array[0]=71;
array[1]=77;
array[2]=72;
array[3]=73;
array[4]=74;
array[5]=75;
return array;
}
int main()
{
int i;
int *numbers;
numbers = get_array();
for(i = 0; i < 6; i++)
{
printf("%d ", numbers[i]);
}
}
Upvotes: 0
Reputation: 604
pass in the array as an argument:
void get_array(int array[])
Don't return array, just return. Then call it with :
get_array(numbers);
Upvotes: 2
Reputation: 225082
Arrays in C are non-modifiable lvalues. Change int numbers[6]
in main()
to int *numbers
and you'll be fine.
Make sure to free()
it!
Editorial note: It's a bit weird to have that declaration of get_lotto_numbers
in your main
function.
Upvotes: 5