• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

arrays - different size

 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does this code compile and even run ? Arrays are of different size!

 
Henry Wong
author
Marshal
Pie
Posts: 21116
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following line of code...



merely assign the finalvalue reference to the same array object referenced by the initial variable. It does not do an array copy. After the operation both variables will reference the same array object.

Since both are int array varables, the assignment is legal.

Henry
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key is that the variables "initial" and "finalvalue" are both of the same type: int array. They can reference any int array assigned (or re-assigned) to them.

The size of an array has to do with the object created -- not the variable it's assigned to.

Here, an int array is instantiated to length 3, and another int array instantiated to length 2. Initially, references to these objects are assigned to the variables "initial" and "final" value respectively. But there's no reason these can't be switched.

However, in your code, I think you'll find that both of these variables end up referencing the same object. Can you see why?
 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


If you assign an array to a previously declared array reference, the array you're assigning must be the same dimension as the refrence you're assigning it to.



So I do not understand the above statement ? The code seems to work differently.
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Readers,

If you assign an array to a previously declared array reference, the array you're assigning must be the same dimension as the refrence you're assigning it to.


I think here the same dimension means with respect to 1-D, 2-D and so on. It does not refer to the size of the array as in your case the arrays are of size 2 and 3 respectively BUT the important thing to remember is that both have the same dimension.

I really hope that what I have said is right. If not, please correct me.
 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shyam,

Now that you mention it... it does look that you are correct!

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic