Hey guys I got two questions , please anser , what's the difference between when a function takes a variable with * " pointer " , like this :
void function(int *x);
int y;
function (y);
and what's the difference between this and & " ref "
also I want trying to sort an array from min to max using a sorting algorithm
here's the code , what's wrong with it ? it shows 3 3 6 6
Your assignment in line 18 -- you're assigning one index to another, not swapping the values they point at.
Instead of min = j
try
1 2 3
int tmp = x[i + 1];
x[i + 1] = x[i];
x[i] = tmp;
Also you don't need so many variables and your "cout" is in the wrong place. You print out 1 value each pass through the loop while sorting, you should rather wait till your sort is complete then print out your final values. See example below:
you should go through this program step-by-step and than you'll find out what's wrong with that.
i = min = 0
j = 1
x[0] > x[1] -- that's true (5 > 3) and so min = j = 1
... no other comparison will be true; there ain't smaller number than 3
OUTPUT: x[1] = 3
i = min = 1
j = 2
x[1] > x[2] -- false (3 > 7)
... no other comparison will be true; there ain't smaller number than 3 and min is still 1
OUTPUT: x[1] = 3
i = min = 2
j = 3
x[2] > x[3] -- that's true (7 > 6) and so min = j = 3
... no other comparison will be true; there ain't smaller number than 6 and min is still 3
OUTPUT: x[3] = 6
i = min = 3
j = 4
x[3] > x[4] -- false (6 > 8)
... no other comparison will be true; there ain't smaller number than 6 and min is still 3
OUTPUT: x[3] = 6
If you have void function(int *x)
You can call it by passing a pointer. The pointer is the address of an int, e.g.
1 2
int x = 0;
funtcion(&x);
In this case, "&" means "address of"
You may have a function that takes a reference, say void function(int &y) here "&" means reference to.
You call it by doing
1 2
int x = 0;
function(x)
When you're calling this time there's no distinction from how you would pass a normal non-reference, non-pointer argument. However the function you're calling can change the argument. It may help to think of the reference as an automatically generated and de-referenced pointer.
Thanks guys , it worked , I think the program was running fine the only thing is that I tried to do it without the swapping thing , but after doing the swapping , it worked like charm.