| |

VerySource

 Forgot password?
 Register
Search
View: 811|Reply: 5

Novice learning pointer problem

[Copy link]

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-1-19 09:00:02
| Show all posts |Read mode
#include <iostream>
int sub (int *, int *); // Declaring the sub function and having two pointer pointers for integers
int main ()
{
using namespace std;
int a = 100, b = 200;
cout << "Before, print a and b:" << a << "and" << b << "\n";
cout << "Go to sub () ..." << "\n";
sub (&a,&b); // pass the addresses of integers a and b to sub ()
         cout << "After, print a and b:" << a << "and" << b << "\n";
return 0;
}
int sub (int * x, int * y) // x, y is the address of a and b, passed into the function
{
int temp;
temp = * x; // Assign the value at X address to the integer temp
* x = * y; // Assign the value at y address to the memory pointed to by x address
* y = temp; // Assign the value of integer temp to the memory pointed to by y
return * x, * y; // Return the values ​​at x and y addresses
}


Is this understanding correct in the comments ????
Reply

Use magic Report

0

Threads

49

Posts

34.00

Credits

Newbie

Rank: 1

Credits
34.00

 China

Post time: 2020-1-26 01:54:01
| Show all posts
return * x, * y; // Return the values ​​at x and y addresses
return can only return an int value here,
At the same time, because the parameter uses a pointer, the content of the address pointed by x and y has been changed in the function, and there is no need to return! You can change sub to:
void sub (int *, int *);
Reply

Use magic Report

0

Threads

49

Posts

34.00

Credits

Newbie

Rank: 1

Credits
34.00

 China

Post time: 2020-1-26 02:09:01
| Show all posts
Other correct
Reply

Use magic Report

0

Threads

12

Posts

10.00

Credits

Newbie

Rank: 1

Credits
10.00

 Hong Kong

Post time: 2020-1-26 03:18:01
| Show all posts
// Return the values ​​at x and y addresses
Should be the value at the end of the returned y address
Reply

Use magic Report

0

Threads

14

Posts

13.00

Credits

Newbie

Rank: 1

Credits
13.00

 Hong Kong

Post time: 2020-1-26 18:27:02
| Show all posts
No need to return, the values ​​of a and b have been modified
Remove return * x, * y;
int sub (int * x, int * y) changed to void sub (int * x, int * y)
Reply

Use magic Report

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

 Author| Post time: 2020-1-27 12:36:01
| Show all posts
Got it, thank you
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list