array of pointers

J

josh

Hi, for study purpose I try to convert some C code in Java code and I
want to know
if there is a way to convert this:

int x=10,y=100,z=1000;
int *a[3];

a[0] = &x;
a[1] = &y;
a[2] = &z;

cout << "x="<< *a[0] << " y="<< *a[1] << " z="<< *a[2] << endl;

thanks
 
T

Thomas Weidenfeller

josh said:
Hi, for study purpose I try to convert some C code in Java code and I
want to know
if there is a way to convert this:

int x=10,y=100,z=1000;
int *a[3];

a[0] = &x;
a[1] = &y;
a[2] = &z;

No, you have no pointers in Java. Your textbook (you have one?) probably
mentions that.

/Thomas
 
J

Jan =?ISO-8859-1?Q?Thom=E4?=

Hi,

since there are no pointers in Java, there is no way to do something like
that. You can do something similar, with references:
// needs Java 1.5
Integer x = 10;
Integer y = 100;
Integer z = 1000;

Integer[] = new Integer[3];
a[0] = x;
a[1] = y;
a[2] = z;

System.out.println( "x=" + a[0] + " y = " + a[1] + ... );

however, note, that Integer objects are immutalbe, so if you do something
like:
x = 1000;

this will not be reflected when you print out the array, since the array
holds a reference to another object than the x. As i said, there is no way
to create "pointers" to variables.

Best regards,
Jan
Hi, for study purpose I try to convert some C code in Java code and I
want to know
if there is a way to convert this:

int x=10,y=100,z=1000;
int *a[3];

a[0] = &x;
a[1] = &y;
a[2] = &z;

cout << "x="<< *a[0] << " y="<< *a[1] << " z="<< *a[2] << endl;

thanks
 
J

josh

Thomas Weidenfeller ha scritto:
No, you have no pointers in Java.
oh I've no pointers in Java like the C/C++ but in Java objects and
array contains reference to the data pointed.....and in Java I can't
use real address and arithmetic notation.....
Your textbook (you have one?) probably
mentions that
yes I've a book I'm only trying to convert the code :)

Thanks
 
R

Rodrigo Zechin

Hi, for study purpose I try to convert some C code in Java code and I
want to know
if there is a way to convert this:

int x=10,y=100,z=1000;
int *a[3];

a[0] = &x;
a[1] = &y;
a[2] = &z;

cout << "x="<< *a[0] << " y="<< *a[1] << " z="<< *a[2] << endl;

thanks

If you want "mutable" integers, just create a small class like this...
public class MyInt{
public int val; // Or make private and a getter/setter
public MyInt(int v){
this.val=v;
}
}

MyInt x=new MyInt(10), y=new MyInt(100), z=new MyInt(1000);
MyInt a[] = new MyInt[] {x, y, z};
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,268
Messages
2,571,096
Members
48,773
Latest member
Kaybee

Latest Threads

Top