0

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.

2
  • There is a mismatch between get_array and get_lotto_numbers - did you modify your example? Commented Mar 19, 2014 at 23:54
  • 3
    Also, you should probably malloc(6 * sizeof(int)) rather than malloc(6). The latter will only allocate 6 bytes. Commented Mar 19, 2014 at 23:57

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And it might be worth noting that in C int *get_lotto_numbers(); is not a prototype and the function could be called with any argument list and the compiler would (probably) not complain. It's also odd to define a function get_array() and call get_lotto_numbers().
2

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);

1 Comment

This is indeed a simpler way to go about the business when dynamic allocation isn't really needed -- and it isn't here; the array is a (small) fixed size.
0
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]);
      }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.