I'm in the process of preparing a textbook on C/C++
programming for an introductory MIS class and was writing
the chapter on structures. My specific topic was the
differences between using composition and pointers.
To demonstrate, I defined two structures:
car -- composed of engine, body, interior and epa_safety
structures
car_pointer -- composed of pointers to same structures
(Definitions are in attached car.h).
I used the following main function:
// start main file
#include <iostream>
using namespace std;
#include "car.h"
int main()
{
struct engine e1={6,4.1};
struct body b1={"Hunter Green",81,183};
struct interior in1={false,false};
struct epa_safety epa1={0.00};
struct car_pointer mycarptr=
{10210,&e1,&b1,&in1,&epa1};
struct car mycar= {10210, //nSerialNo
{6,4.1},// engine initializers
{"Hunter Green",81,183}, // body initilizers
{false,false} // interior initializers
};
cout << mycar.nSerialNo << endl;
cout << mycarptr.nSerialNo << endl;
return 0;
Quote:
}
// end main file
For some reason, however, the interior structure embedded
within the mycar object did not initialize the same way
the interior object in1 did. I would have expected the
non-initialed struct interior elements (i.e., bCDPlayer
and szColor[]) to have been initialized to the zero-
equivalents. Instead, running to the cout statements, I
found:
mycar.in.bCDPlayer == true
mycar.in.szColor == four garbage characters, followed by
NULs
On the other hand, I found:
in1.bCDPlayer == false
in1.szColor ==> all NUL'd out
(Just as I would haver expected.)
Does anyone know of any obvious reasons that these
elements might not have initialized the same way, given
they had the same initialization list (i.e.,
{false,false})?
Thanks!