question about structure and pointers

In the protype:
void vol(box*);
the pointer is to the right where pointers are usually to the left. I am confused as to its meaning. I presume it means that it is a pointer to box but then the function definition introduces another structure
void vol(box *mystruc)
and I am unclear as to what is the pointer and what is being pointed at.

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
34
35
36
  #include <iostream>
struct box
{
	char maker[40];
	float height;
	float width;
	float length;
	float volume;
};

void value (box);
void vol(box*);

using namespace std;

int main()
{
	box woodbox = { "Poad", 5.5, 10.0, 15.7, 0 };
	vol(&woodbox); array
	value(woodbox);
	return 0;
}

void value(box mystruc)
{
	cout << "The maker of the box is " << mystruc.maker << ". " << endl;
	cout << "Height is " << mystruc.height << endl;
	cout << "Width is " << mystruc.width << endl;
	cout << "Length is " << mystruc.length << endl;
	cout << "Volume is " << mystruc.volume;
}

void vol(box *mystruc)
{
	(*mystruc).volume = (*mystruc).height * mystruc->width * mystruc->length;
}
box *mystruc is exactly the same as writing box* mystruc. When the function is declared before main there is no need to mention the name of the parameter. The only thing that is necessary here is the type of the parameter, box* (pointer to box).
Last edited on
Got it, thank you very much. I have another question. The above program outputs these results:
The maker of the box is Poad.
Height is 5.5
Width is 10
Length is 15.7
Volume is 863.5

If I change the vol function so that it isn't a pointer, I get these results:
The maker of the box is Poad.
Height is 5.5
Width is 10
Length is 15.7
Volume is 0

So the vol function does not work correctly without the pointer. The code is below. Why is that?

#include <iostream>
struct box
{
	char maker[40];
	float height;
	float width;
	float length;
	float volume;
};

void value(box);
void vol(box);

using namespace std;

int main()
{
	box woodbox = { "Poad", 5.5, 10.0, 15.7, 0 };
	vol(woodbox);//function call that passes the address of the woodbox array
	value(woodbox);
	return 0;
}

void value(box mystruc)
{
	cout << "The maker of the box is " << mystruc.maker << ". " << endl;
	cout << "Height is " << mystruc.height << endl;
	cout << "Width is " << mystruc.width << endl;
	cout << "Length is " << mystruc.length << endl;
	cout << "Volume is " << mystruc.volume;
}

void vol(box mystruc)
{
	mystruc.volume = mystruc.height * mystruc.width * mystruc.length;
}

Since you're now passing the parameter by value any changes made in the function are lost when the function returns. You may want to consider passing the parameter by reference.

1
2
3
4
5
6
7
8
...
void vol(box &);
...

void vol(box &mystruc)
{
	mystruc.volume = mystruc.height * mystruc.width * mystruc.length;
}


Yes, that works. Thank you very much.
Topic archived. No new replies allowed.