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;

//  ...

    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.

Edited by grib: Clumsy posting, sorry

7 Years
Discussion Span
Last Post by grib

I still don't understand the question. Please be more specific.

I do see that you don't null terminate can->name in putCandy() so technically can->name is a simple char array not a string. Try fixing that and see what happens. If it doesn't fix things then post with a specific question.


Thank you both; those are both working solutions. As it happens, the text I'm using (C++ Primer Plus, Prata) puts off exploring the string class until a fair bit later, and I AM looking forward to not cobbling up every single string I need out of char-array tinkertoys. That being said, I SHOULD have known to terminate the character array, though.

Also, pardon my lack of clarity. I began by buzzing off a decent post about a dereferencing problem I had, but I then figured it out while I described it. I compiled the solution, and would up with the non-terminated char array problem that resulted in the second line of output returning Name: Millenium Munchw\ " when it should have returned Name: Millenium Munch .

In any case, it's returning exactly what it ought to be returning now. Thank you again for the quick responses!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.