How to pass and return arrays in c?
Go to solution
Solved by colonel_mortis,
You can't pass arrays by value in C, but you can pass a pointer to the array.
void sort(int* arr, int len) { // you can read and update arr[0]..arr[len-1] in here. // Simple bubblesort implementation: for (int end = len; end > 1; end--) { for (int i = 1; i < end; i++) { if (arr[i-1] > arr[i]) { int tmp = arr[i]; arr[i] = arr[i-1]; arr[i-1] = tmp; } } } } int main() { int nums[5] = {5, 8, 1, 3, 4}; sort(nums, 5); }
You can play with this code here:
(sorry, embedding repl.it is currently an admin-only feature, but I'm working on it).
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now