I am begining with C these days and I am cool with it.
I understand the concept of pass by value and pass by reference.
In pass by reference, one directly makes changes to the contents using the address.
Take a look at the code below.
In this, I havent used call by reference,yet the contents of the main array changes.
I have no explanation for this. Is this some bad programming practice?
If yes then kindly show me how to get it the correct way.
This is a snippet which I wrote and I am not quiet sure how it works,but it does.
I think you have to first look into the array in c and c++.
Actually when you point "array", this is fist address of "array" variable. that means if you do printf("%d", **array); then value will be the same as array.
So when you pass array to method you pass pointer of that array and that is why this is working.
It's not actually pass-by-reference. It is mimicking pass-by-reference by passing the value of the pointer, as you have already been told.
You can do the same in Java™, but Java™ arrays are real objects.
Joined: Dec 29, 2009
Thanks for replies.
I am still not able to decide if this way of coding is a normal form in C/C++ and not a bad practice.
I am asking this,because if this is possible, then I don't really find a good reason to get involved in pointer arithmetics and other pointer relates stuff.
So there has to be some advantage by using pointers, maybe speed or maybe avoiding memory leaks can you guys please help me with this?
Is there any other way which I can do it.
Joined: Oct 13, 2005
You can use indices as in array[i][j]. But that simply hides the pointers, rather like using a sort of syntactic sugar.
Pointers are there because C is intended to access the actual memory location, instead of using assembler.
subject: How do the values change even if I am not passing the arrays with reference?