Assignment is to create a function that accepts a pointer to object "Sample", but when calling the function I need an "address of" as the argument. Why does this work?
I thought that if the function expects a pointer, I should send a pointer like this "showSample(*X)", but this doesn't compile, "showSample(&X)" does.
This has me confused.
This is because of how pointer initialization works:
1 2 3 4 5 6
Sample X;
Sample Y;
Sample* sptr = &X; //Provide memory address so sptr knows what to point to
//Now you could do
// *sptr //Dereference pointer
// sptr = &Y //Point to Y instead
showSample takes a pointer parameter. Therefore, you need to provide something the parameter can be initialized with, the memory address of the variable.
1 2
showSample(sptr); //memory address held in sptr will now be passed
showSample(&X) //Causes Sample* input = &X
showSample(*X) is not possible because X is not pointer; it cannot be dereferenced as one. Even then, you would be passing to the parameter what is being returned by *X, i.e. whatever it was pointing to, not the address.
Your answer made me think of something probably mentioned long ago in the book.
Am I right in thinking that when you pass an argument to a function, the argument initializes the function parameter, it doesn't "flow through" into the function. I believe that's what's been tripping me up.