Returning an array using C

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

    In your case, you are creating an array on the stack and once you leave the function scope, the array will be deallocated. Instead, create a dynamically allocated array and return a pointer to it.

    char * returnArray(char *arr, int size) {
        char *new_arr = malloc(sizeof(char) * size);
        for(int i = 0; i < size; ++i) {
            new_arr[i] = arr[i];
        }
        return new_arr;
    }
    
    int main() {
    
        char arr[7]= {1,0,0,0,0,1,1};
        char *new_arr = returnArray(arr, 7);
    
        // don't forget to free the memory after you're done with the array
        free(new_arr);
    
    }
    

提交回复
热议问题