Seems that I'm going to get hung up on every CandyBar exercise in this book I'm working through. Such is life.
I'm doing something stupid, and I can't see it. Something appends garbage into my structure's first field when I try to give it the defaults.
#include <iostream>
const int ArSize = 80;
struct CandyBar
{
char name[ArSize];
double weight;
int calories;
};
void putCandy(CandyBar * can, char * ch = "Millenium Munch",
double wt = 2.85, int cal = 350);
void showCandy(const CandyBar * can);
// ...
int main()
{
using namespace std;
cout << "Here are the defaults for CandyBar.\n";
CandyBar a;
putCandy(&a);
showCandy(&a);
// ...
return 0;
}
// ...
void putCandy(CandyBar * can, char * ch, double wt, int cal)
{
using namespace std;
for (int i = 0; ch[i] != '\0' && i < ArSize; i++)
can->name[i] = ch[i];
can->weight = wt;
can->calories = cal;
}
void showCandy(const CandyBar * can)
{
using namespace std;
cout << "Name: " << can->name << endl;
cout << "Weight: " << can->weight << ", calories: " << can->calories;
cout << endl;
}
// ...
...which results in:
Here are the defaults for CandyBar.
Name: Millenium Munchw\ "
Weight: 2.85, calories: 350
My ordinary input via values fed to putCandy then works fine.
What am I missing here?
Sorry, my original problem was with dereferencing, so the thread title, which I forgot to change, is irrelevant to my problem.