Return Array in C?

前端 未结 4 713
春和景丽
春和景丽 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条回答
  •  旧时难觅i
    2021-01-07 05:52

    You can not assign to an array from an expression:

    int recievedNumbers[MAXSIZE];
    ...
    recievedNumbers = getACOfNumber(256);
    

    Instead:

    memcpy(receivedNumbers, getACOfNumber(256), sizeof(receivedNumbers));
    

    An notice that you are using a local array whose lifetime ends with the function, change to

    static int theArray[100];
    

    or better yet

    int *theArray = calloc(100, sizeof(*theArray)); /* Zero initializes the array */
    

    don't forget to call free at the end:

    int *temp = getACOfNumber(256);
    
    memcpy(receivedNumbers, temp, sizeof(receivedNumbers));
    free(temp);
    

    But why don't you pass the original array to the function?:

    getACOfNumber(receivedNumbers);
    ...
    void getACOfNumber(int *theArray) {
    

提交回复
热议问题