I want to write a program that uses Pointers and when I change the value of a pointer, the others follow that pointer; here is my code:
int * M1 = new int(1) ;
int * M2 = new int(2) ;
int * M3 = new int(3) ;
int * M4 = new int(4) ;
int * M5 = new int(5) ;
int * M6 = new int(6) ;
int * M7 = new int(7) ;
int * M8 = new int(8) ;
int * M9 = new int(9) ;
int * M10 = new int(10) ;
M1 = M2 = M3 = M4 = M5;
M6 = M7 = M8 = M9 = M10;
*M5 = *M10; // now *M1 : *M5 is equal *M10
*M10 = 120; // this only changes *M6 : *M10 but I want *M1 : *M5 changes too
how can I change whole *M1 : *M10 without using loop??
CodePudding user response:
I don't think you can do what you're asking in the way you're asking it. Pointers are kind of like labels for memory locations, and moving one label doesn't change the location any of the other labels are pointing to. Let's visualize the starting state:
1 <- M1
2 <- M2
3 <- M3
4 <- M4
5 <- M5
6 <- M6
7 <- M7
8 <- M8
9 <- M9
10 <- M10
On the M1 = M2 = M3 = M4 = M5
line, you're moving the first four pointers (just labels) to point where M5 is pointing at (call it location 5). Similarly for the next line, to point M6:M9 to where M10 is pointing at (call it location 10).
1 <-
2 <-
3 <-
4 <-
5 <- M1,M2,M3,M4,M5
6 <-
7 <-
8 <-
9 <-
10 <- M6,M7,M8,M9,M10
With your line *M5 = *M10
, you change just the value at M5's location, location 5. The location of all the labels doesn't change.
1 <-
2 <-
3 <-
4 <-
10 <- M1,M2,M3,M4,M5
6 <-
7 <-
8 <-
9 <-
10 <- M6,M7,M8,M9,M10
Your last line does the same, for location 10:
1 <-
2 <-
3 <-
4 <-
10 <- M1,M2,M3,M4,M5
6 <-
7 <-
8 <-
9 <-
120 <- M6,M7,M8,M9,M10
If you want to move those labels again, you'll need to move them individually. They point to a location, but are each their own separate labels. The shortest way to do what you want from the end of your program is:
M1 = M2 = M3 = M4 = M5 = M10;
1 <-
2 <-
3 <-
4 <-
10 <-
6 <-
7 <-
8 <-
9 <-
120 <- M1,M2,M3,M4,M5,M6,M7,M8,M9,M10
If you want all of them to point at that last location by pointing them to M5's location, you can do that by modifying your code a little bit to move M5 first:
int * M1 = new int(1) ;
int * M2 = new int(2) ;
int * M3 = new int(3) ;
int * M4 = new int(4) ;
int * M5 = new int(5) ;
int * M6 = new int(6) ;
int * M7 = new int(7) ;
int * M8 = new int(8) ;
int * M9 = new int(9) ;
int * M10 = new int(10) ;
M5 = M10; // M5 now points to location 10
M1 = M2 = M3 = M4 = M5; // M1:M4 now point to location 10
M6 = M7 = M8 = M9 = M10; // M6:M9 now point to location 10
*M5 = *M10; // This does nothing, since they already point to the same location
*M10 = 120; // All values point to location 10, which now holds the value 120
The resulting diagram here is:
1 <-
2 <-
3 <-
4 <-
5 <-
6 <-
7 <-
8 <-
9 <-
120 <- M1,M2,M3,M4,M5,M6,M7,M8,M9,M10