+ 2

Local variables in c

This code is working fine but it should not because I have made array x as local variable and still when I am doing operations like push,pop using functions outside main I am getting answer repeatedly after performing operations like adding elements in x using x and when I am printing it later it gives me the correct answer. https://code.sololearn.com/c3RvueHucJ14/?ref=app

21st Aug 2018, 12:26 PM
harshit
harshit - avatar
8 Respostas
+ 3
harshit as Hatsy Rei stated, arrays are passed by reference so functions are accessing the original directly, not a copy as what happens with other arguments. Usually 8 bytes or less are copied to the stack, otherwise, they are copied to the heap & that address gets passed, depending on the compiler. The reason arrays are different is because they are treated as a pointer that can be offset so passing the pointer is how you must pass them. You can switch between pointer access or array access on every pointer or array in C and C++. It is also why the size of an array is only know in the function that allocates it as any other fuction only has a pointer.
21st Aug 2018, 6:20 PM
John Wells
John Wells - avatar
+ 4
It depends on whether you want to modify the array within main or not. Assuming you do and the way your code is written suggests you do, it is fine. If you do not want your array to get modified, you should make a local copy of it first and make changes to it.
21st Aug 2018, 7:19 PM
John Wells
John Wells - avatar
+ 3
Arrays, when passed to functions, decay to pointers. Any changes done to arrays in functions will affect the original array.
21st Aug 2018, 4:54 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
You passed the local array to the functions as an argument, so it would work as the functions have access to x. If you use the global array, you don't even need to pass x as an argument to the functions since x is readily visible.
21st Aug 2018, 1:45 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
So my code is correct when passing the array or it requires some changes?
21st Aug 2018, 6:59 PM
harshit
harshit - avatar
0
I know that but see,once I pass x as an argument in push it is storing value of first element in x which is a local variable in push function.Now again when I am printing using printstack function why is it able to print as I have not returned value of x before.
21st Aug 2018, 4:35 PM
harshit
harshit - avatar
0
John Wells sir, please take a look at this.
21st Aug 2018, 4:35 PM
harshit
harshit - avatar
0
Ok
8th Oct 2020, 10:19 AM
OKEKE LOTANNA