Returning an array using C

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

    I am not saying that this is the best solution or a preferred solution to the given problem. However, it may be useful to remember that functions can return structs. Although functions cannot return arrays, arrays can be wrapped in structs and the function can return the struct thereby carrying the array with it. This works for fixed length arrays.

        #include 
        #include 
        #include 
    
        typedef
        struct 
        {
            char v[10];
        } CHAR_ARRAY;
    
    
    
        CHAR_ARRAY returnArray(CHAR_ARRAY array_in, int size)
        {
            CHAR_ARRAY returned;
    
            /*
            . . . methods to pull values from array, interpret them, and then create new array
            */
    
            for (int i = 0;  i < size; i++ )
                returned.v[i] = array_in.v[i] + 1;
    
            return returned; // Works!
        } 
    
    
    
    
        int main(int argc, char * argv[])
        {
            CHAR_ARRAY array = {1,0,0,0,0,1,1};
    
            char arrayCount = 7;
    
            CHAR_ARRAY returnedArray = returnArray(array, arrayCount); 
    
            for (int i = 0; i < arrayCount; i++)
                printf("%d, ", returnedArray.v[i]);  //is this correctly formatted?
    
            getchar();
            return 0;
        }
    

    I invite comments on the strengths and weaknesses of this technique. I have not bothered to do so.

提交回复
热议问题