Return Array in C?

前端 未结 4 688
春和景丽
春和景丽 2021-01-07 05:21

I cant return array in c,i am quite new to C so i probably do some kind of funny mistake, here is the code:

#define MAXSIZE 100
int recievedNumbers[MAXSI         


        
4条回答
  •  悲&欢浪女
    2021-01-07 05:42

    The compiler is complaining about the line

    recievedNumbers = getACOfNumber(256);
    

    You cannot use the = operator to assign the contents of an array; an array expression may not be the target of an assignment operation. Also, the result of getACOfNumber is an int *, which is not the same type as int [100].

    This could work if you declared receivedNumbers as

    int *recievedNumbers;
    

    In that case you're assigning a pointer to a pointer, which should work.

    But, you have another problem:

    int* getACOfNumber(int theNumber) {
      bool done = false;
      int i = 0;
      int theArray[100];
      ...
      return theArray;
    }
    

    This will not do what you expect. Once the getACOfNumber function exits, theArray no longer exists - the pointer you return is no longer valid.

    IMO, your best bet is to pass the array as a parameter to getACOfNumber and update it directly in the function:

    getACOfNumber( 256, receivedNumbers, MAXSIZE );
    ...
    void getACOfNumber( int number, int *theArray, size_t max )
    {
      bool done = false;
      size_t i = 0;
      while ( i < max && !done )
      {
        ... // use existing code
      }
    }
    

提交回复
热议问题