Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Ashish Schottky
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic