How to return an array from a function?

后端 未结 5 643
说谎
说谎 2020-11-22 13:11

How can I return an array from a method, and how must I declare it?

int[] test(void); // ??
5条回答
  •  失恋的感觉
    2020-11-22 13:56

    Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.

    So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:

    int *gnabber(){
      static int foo[] = {1,2,3}
      return foo;
    }
    

提交回复
热议问题