Why is address passed when parameter is pointer?

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.

Thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

struct Sample
{
	int first;
	int second;
	char* sPtr;
};

	void showSample(Sample* input)
	{
		cout << endl;
		cout << "first = " << input->first;
		cout << endl;
		cout << "second = " << input->second;
		cout << endl;
		cout << "sPtr = " << input->sPtr;
		cout << endl;
		cout << endl;
	}

int main(void)
{

	Sample X;

	X.first = 1;
	X.second = 2;
	char* s = "xPointer";
	X.sPtr = new char[strlen(s)+1];
	strcpy_s(X.sPtr, strlen(s)+1, s);
	showSample(&X);
        return 0;
}
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.

Thanks
You guys are the BEST.
Last edited on
Topic archived. No new replies allowed.