0
How to print each element of array increased by 2, by function call?
I want to create a some function which takes one argument, an array with length of 5. When the function is called, it prints a given array with each element increased by 2. Here is my code: void do_it(int arr[5]) { for(int i = 1; i < 5; i++) { arr[i]+=2; } return arr[]; } int main() { printf("%d", do_it([8, 4, 15, 77, 100])); } But it causes a compile error. why?
2 Antworten
+ 2
- The function is void but you return something (the array)
- The i variable in the for loop should start with 0 because arrays start from 0 instead of 1
- To return an array you just write the array name without [], you don't actually have to return the array as you always pass an array by reference meaning you can edit it directly
- You can't print out an array like that, use a for loop to loop through the array
- You used [] instead of {} to declare an array
- You can't pass an anonymous array like that you need to type cast it e.g. do_it((int[]) {1, 2, 3, 4, 5}), although this is useless as you can't access the anonymous array so declare a normal one then use it
Here is a link to the fixed code:
https://code.sololearn.com/c0hEv4vYIKV7/#c
0
TurtleShell thank you for your help.