Hey guys, my professor had a question on my test that basically tested my understand of pointers. (I won't write the program in its entirety just the main piece.
*q=22
p=q
*p=33
cout << *q << *p << endl;
What's the output?
At first I thought it was the addresses of p and q but since the pointers themselves were being initialized I said the output was 2233.
Was I right? If not, what's it suppose to be?
If you've had it on your brain, perhaps you should try it out in code.
1 2 3 4 5
*q = 22 // assign the value 22 to the area of memory pointed to by q.
p = q // p points to the same area of memory as q.
*p = 33 // assign the value 33 to the area of memory pointed to by p and q.
// because p and q point to the same area of memory.
I tried to test that code in codeblocks, The output should be 3333, oddly enough when I tried to use the line (cout<<*p<<*q<<endl;) my debugger threw several strange errors about *q not being initialized. was anyone able to test this code? it seamed to run fine after I separated it into two separate cout statements (output was 3333) but could anyone run this in a single cout?
I also tried the code in visual basic C++ and that I couldn't get to run at all.
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int // define initial values
holder1 = 33,
holder2 = 22;
int* // initialize pointers
p = &holder1,
*q = &holder2;
// assign them now!
p = q;
// show me result
cout << *p << endl << *q;
// pause the program
cin.ignore();
return 0;
}
I tried to test that code in codeblocks, The output should be 3333, oddly enough when I tried to use the line (cout<<*p<<*q<<endl;) my debugger threw several strange errors about *q not being initialized. was anyone able to test this code? it seamed to run fine after I separated it into two separate cout statements (output was 3333) but could anyone run this in a single cout?
Well, these were snippets. In order to "test" the code without running into undefined behavior you would have to add a few things:
> I tried to test that code in codeblocks, The output should be 3333, oddly
> enough when I tried to use the line (cout<<*p<<*q<<endl;) my debugger
> threw several strange errors about *q not being initialized.
> was anyone able to test this code?