Two Laptop Bag*
The moose likes C / C++ and the fly likes How do the values change even if I am not passing the arrays with reference? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "How do the values change even if I am not passing the arrays with reference?" Watch "How do the values change even if I am not passing the arrays with reference?" New topic
Author

How do the values change even if I am not passing the arrays with reference?

Ashish Schottky
Ranch Hand

Joined: Dec 29, 2009
Posts: 93
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.
please help.
nishit charania
Greenhorn

Joined: Feb 10, 2010
Posts: 9
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[0][0].
So when you pass array to method you pass pointer of that array and that is why this is working.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37970
    
  22
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.
Ashish Schottky
Ranch Hand

Joined: Dec 29, 2009
Posts: 93
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.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37970
    
  22
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do the values change even if I am not passing the arrays with reference?
 
Similar Threads
Help with Arrays!
How to add a merge array from 2 others arrays and print it
C question
how to insert symbols
Passing Array References, javaprepare Q.30