Why is the third element short 256

I wrote this as part of an assignment and I can't seem to find the bug in it. What is happening is that the third element of the structure (the integer) is coming up 256 short when I display it to the console. If I add the line after the first initialization, treat[0].bar_calories = 290, then the output will be correct (290) otherwise it displays 34.



#include <iostream>
struct CandyBar
{
char bar_name[20];
float bar_weight;
int bar_calories;
};

int main()
{
using namespace std;
CandyBar *treat = new CandyBar[3];

treat[0] = { "Snickers", 2.5, 290 };
treat[1] = { "Peanut Brittle", 1.25, 300 };
treat[2] = { "M&M's", 3.25, 360 };

cout << "Name of candy bar: " << treat[0].bar_name << endl;
cout << "Weight of candy bar: " << treat[0].bar_weight << " oz." << endl;
cout << "Calories of candy bar: " << treat[0].bar_calories << endl;
cout << endl;
cout << "Name of candy bar: " << treat[1].bar_name << endl;
cout << "Weight of candy bar: " << treat[1].bar_weight << " oz." << endl;
cout << "Calories of candy bar: " << treat[1].bar_calories << endl;
cout << endl;
cout << "Name of candy bar: " << treat[2].bar_name << endl;
cout << "Weight of candy bar: " << treat[2].bar_weight << " oz." << endl;
cout << "Calories of candy bar: " << treat[2].bar_calories << endl;
delete treat;

cin.get();

return 0;]
I don't see anything that would cause that behavior, although you do have undefined behavior here. Are you sure you've compiled against the latest source?

If you use new[], you must use delete[]
use code tags for writing code please
Topic archived. No new replies allowed.