Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Missing Double Pointers

 
Muhammad Ali
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am almost an intermediate level programmer in Java. I come from C++ background and was wondering how can you achieve the following in Java:
void assignString (char **pString)
{
pString = new char[10];
*pString[0] = 'A';
*pString[1] = 'l';
*pString[2] = 'i';
*pString[3] = 0;
}
You can call this code as follows:
char *str;
assignString (&str);


A Java equivalent should have been as follows. But as you know "msg" will be local reference and will exist in this method only.
void assingString (String msg)
{
msg = new String ("Ali");
}
My question is why you don't have double references in Java? And how can you overcome this limitation?
One anoter <big>big</big> question: How can you pass primitive data types by reference? I heard about the wrapper classes but would like to see some code.
Muhammad Ali Shah
Karachi, Pakistan
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Muhammand,
From your code example, you want a String to contain "Ali" upon returning from assignString. To do this in Java, I would recommend the following code sample.

You can use the same technique for primitives. Create a primitive array of one element and pass this in. When you pass in the array, you're passing in a reference to the content of the array. With the array reference, you're allowed to change the content of the array, but not what the array points to.
Hope this helps.
-Peter

 
Muhammad Ali
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. Now I can fully understand how you can use two, three and multi dimensional arrays to have the same affect as two, three or multi level pointers.
There is one question that still needs to be answered. Is there any other way (except arrays) to pass primitives by reference?
Thanks once again...
Ali.
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create your own primitive wrapper with set/get methods.

Output:
Bef executing modify(): 1.0
Aft executing modify(): 2.0
-Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic