samedi 30 mars 2019

Why does Visual Studio give unexpected output for this C++ code?

I was learning about pointers and testing out some code from an online video. When the teacher ran his code from an online ide, he produced different results on the 4th line of output. When I ran my code on a random online ide (different from that of the teacher's), I got the same 4th line of output the teacher got. This output should be the right output, so why do I get the wrong output in Visual Studio 2017.

 #include <iostream>

 using namespace std;

 int main() {


int a = 5, b = 7, c = 10, d = 14;

cout << a << " " << b << " " << c << " " << d << endl;

int *pa = &a, *pb = &b, *pc = &c, *pd = &d;

cout << &a << " " << &b << " " << &c << " " << &d << endl;

cout << pa << " " << pb << " " << pc << " " << pd << endl;

pa++;
pb++;
pc++;
pd++;

int da = *pa;
int db = *pb;
int dc = *pc;
int dd = *pd;


cout << da << " " << db << " " << dc << " " << dd << endl;
cout << &da << " " << &db << " " << &dc << " " << &dd << endl;

getchar();

return 0;

}

Teacher's results (what I expected):

5 7 10 14                                                                               
0x7fff7336d390 0x7fff7336d394 0x7fff7336d398 0x7fff7336d39c                             
0x7fff7336d390 0x7fff7336d394 0x7fff7336d398 0x7fff7336d39c                             
7 10 14 7  <----- Correct output                                                                         
0x7fff7336d3a0 0x7fff7336d3a4 0x7fff7336d3a8 0x7fff7336d3ac      

My results:

5 7 10 14
010FFC44 010FFC38 010FFC2C 010FFC20
010FFC44 010FFC38 010FFC2C 010FFC20
-858993460 -858993460 -858993460 -858993460    <------ Weird values
010FFBE4 010FFBD8 010FFBCC 010FFBC0

P.S. I know that the second "7" in the 4th line of output from the teacher's results will not always be "7", since I'm accessing memory I don't really know about. The teacher said that the value could be 7 or 10 or 14. I'm also wondering, why is it only limited to those numbers, why can't that number be some random number or garbage value?

Aucun commentaire:

Enregistrer un commentaire