Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where's the logical error in the for loop

public class Client
{
    public string nome;
}

Client j, h, m, n;
j = h = m = n = new Client();

Client[] c= new Client[]{j,h,m,n};
int[] n = new int[c.Length];

for (int i = 0; i < c.Length; ++i)
{
    n[i] =i;
    c[i].nome = "Client"+i;

}

In the output of n = 0,1,2,3;

but in the output of c = Client4,Client4,Client4,Client4

I'm not a freshman in programming, but I can't figure it out why it isn't concatenating each i value. I can't explain to my self. there is c[i], it should work.

Can anyone help with this?

like image 730
Belarmino Vicenzo Avatar asked Mar 06 '23 23:03

Belarmino Vicenzo


1 Answers

The code:

j = h = m = n = new Client();

creates the j, h, m and n references to a single new object.

Hence, the line c[i].nome = "Client"+i; will set the nome field of that single object, overwriting all the changes already done to it by previous iterations of the loop. In other words, what you have is:

 j ---+
      |    +-------------+
 h ---+--> | single item |
      |    +-------------+
 m ---+
      |
 n ---+

If you want distinct objects, you need to use something like:

j = new Client();
h = new Client();
m = new Client();
n = new Client();

That way, when you change one of the objects, it won't affect the others:

      +------+         +------+
j --> | item |   h --> | item |
      +------+         +------+
      +------+         +------+
m --> | item |   n --> | item |
      +------+         +------+

And, as an aside, if you're looking for a source-size-efficient way of doing this (as seems to be the case from your comments), you can just try getting rid of the middle men.

There's no need for those j/h/m/n temporary references and no real excuse for using single-character variable names anyway. Well, other than i, of course :-)

That would be something like::

Client[] clientArray = new Client[] {
    new Client(), new Client(), new Client(), new Client()
};
int[] numArray = new int[clientArray.Length];
for (int i = 0; i < clientArray.Length; ++i) {
    numArray[i] = i;
    clientArray[i].nome = "Client" + i;
}
like image 59
paxdiablo Avatar answered Mar 17 '23 03:03

paxdiablo