Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better explanation of C++ Pointer function?

Tags:

c++

c

pointers

I am working on a problem for my C++ homework that involves pointers. I am not asking for anyone to do my work, but just some help understanding the problem.

The problem is to write a function

void sort2(double* p, double* p) //First off I am assuming the second "p" is a typo and       should be a q

This function will receive two pointers and sorts the values to which they point. Example, if you call sort2(&x, &y) then x <= y after the call.

What I am wondering is, if the pointers are being de-referenced by the function already, am I just comparing x and y and not their memory addresses? If not how do I compare the memory addresses?

like image 575
Samuel L Jackson Avatar asked Feb 11 '14 03:02

Samuel L Jackson


2 Answers

You are passing the addresses of the 2x double variables, so that the sort2() function can swap the values at source.

This way, when the sort function is called like so:

sort2(&x, &y)

The function can access the caller's memory addresses for x and y and swap the values stored there, if necessary.

However, if the function just took double parameters by value, i.e.

void sort2(double p1, double p2)

then, although the function could still compare and swap the values around, there is no way that sort2() could pass BOTH the new values back to its caller with its current signature, since p1 and p2 are copied by value onto the stack and will be lost when the function returns.

The sort function accesses the values of the pointer variables by de-referencing them, e.g.

if (*p1 > *p2) {
   // swap / sort etc.
   double swap = *p2;
   *p2 = *p1;
   *p1 = swap;
}

And yes, you are correct, the second p is almost certainly a typo.

like image 72
StuartLC Avatar answered Sep 21 '22 12:09

StuartLC


Declaring a function with like: void sort2(double *p, double *q) { takes in two double pointers. When you call the function like this: sort2(&x, &y) you are not dereferencing the pointers, but referencing the variables. For example:

void sort2(double *p, double *q) {
  some_code;
}

int main(int argc, const char *argv[]) {
  double x = 0.2;
  double y = 0.4;
  sort2(&x, &y); //x's and y's addresses in memory are being passed to sort2
  return 0;
}

To compare x and y's memory addresses after the fact then you would have to reference them in some sort of condition like this:

if(&x <= &y)
  do_something;
like image 36
IZeeke Avatar answered Sep 20 '22 12:09

IZeeke