简体   繁体   English

从函数返回数组到C主程序?

[英]returning array from function to main in C?

what is the method to return an array to main? 将数组返回给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. 任何意见将有助于谢谢。

Arrays in C are non-modifiable lvalues . C中的数组是不可修改的左值 Change int numbers[6] in main() to int *numbers and you'll be fine. main() int numbers[6]更改为int *numbers ,就可以了。

Make sure to free() it! 确保free()它!

Editorial note: It's a bit weird to have that declaration of get_lotto_numbers in your main function. get_lotto_numbers注:在您的main函数中有get_lotto_numbers声明很奇怪。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM