+ 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
8 Answers
+ 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.
+ 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.
+ 3
Arrays, when passed to functions, decay to pointers. Any changes done to arrays in functions will affect the original array.
+ 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.
+ 1
So my code is correct when passing the array or it requires some changes?
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.
0
John Wells sir, please take a look at this.
0
Ok