Returning an array using C

前端 未结 8 1091
你的背包
你的背包 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:22

    You can do it using heap memory (through malloc() invocation) like other answers reported here, but you must always manage the memory (use free() function everytime you call your function). You can also do it with a static array:

    char* returnArrayPointer() 
    {
    static char array[SIZE];
    
    // do something in your array here
    
    return array; 
    }
    

    You can than use it without worrying about memory management.

    int main() 
    {
    char* myArray = returnArrayPointer();
    /* use your array here */
    /* don't worry to free memory here */
    }
    

    In this example you must use static keyword in array definition to set to application-long the array lifetime, so it will not destroyed after return statement. Of course, in this way you occupy SIZE bytes in your memory for the entire application life, so size it properly!

提交回复
热议问题