Returning an array using C

前端 未结 8 1203
你的背包
你的背包 2020-11-21 04:45

I am relatively new to C and I need some help with methods dealing with arrays. Coming from Java programming, I am used to being able to say int [] method()in o

8条回答
  •  無奈伤痛
    2020-11-21 05:21

    Your method will return a local stack variable that will fail badly. To return an array, create one outside the function, pass it by address into the function, then modify it, or create an array on the heap and return that variable. Both will work, but the first doesn't require any dynamic memory allocation to get it working correctly.

    void returnArray(int size, char *retArray)
    {
      // work directly with retArray or memcpy into it from elsewhere like
      // memcpy(retArray, localArray, size); 
    }
    
    #define ARRAY_SIZE 20
    
    int main(void)
    {
      char foo[ARRAY_SIZE];
      returnArray(ARRAY_SIZE, foo);
    }
    

提交回复
热议问题