wrote code, compiles but no output......any ideas?

So I wrote this program about candy bars and it compiles but displays nothing, no error messages. Yes, I'm new to C++ but I think I wrote this program correctly. But maybe not........Any suggestions?


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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <cstdlib>
#include <iostream>
#include <string>


struct candybar
{
std::string name;
float weight;
int cals;
};

int main(int argc, char** argv) {

using namespace std;

candybar * snack = new candybar[3];
candybar * p_snack = &snack[0];

p_snack->name = "Twix";
p_snack->weight = 1.8;
p_snack->cals = 278;

p_snack = &snack[1];
p_snack->name = "BabyRuth";
p_snack->weight = 2.1;
p_snack->cals = 275;

p_snack = &snack[2];
p_snack->name = "KitKat";
p_snack->weight = 2.8;
p_snack->cals = 404;

p_snack = &snack[3];
p_snack->name = "Butterfinger";
p_snack->weight = 3.8;
p_snack->cals = 495;


p_snack = &snack[0];
cout << "Candybar: " << p_snack->name << ", cals: " << p_snack->cals << ", weight: " << p_snack->weight << endl;
p_snack = &snack[1];
cout << "Candybar: " << p_snack->name << ", cals: " << p_snack->cals << ", weight: " << p_snack->weight << endl;
p_snack = &snack[2];
cout << "Candybar: " << p_snack->name << ", cals: " << p_snack->cals << ", weight: " << p_snack->weight << endl;
p_snack = &snack[3];
cout << "Candybar: " << p_snack->name << ", cals: " << p_snack->cals << ", weight: " << p_snack->weight << endl;


return 0;
}
Does the ouput window flash too quickly and disappear?

Add these lines in your code at the end just before return 0; statement and then compile & run the program.

1
2
cin.ignore();
cin.get();


Do respond back if it does/doesn't work. :)
No, its sit there with this:

/cygdrive/C/Program Files/NetBeans 6.9.1/ide/bin/nativeexecution/dorun.sh: line 33: 4072 Segmentation fault (core dumpted sh "${SHFILE}"
Added,,,,,,,,,,,,,,,,same message but different................: line 33: 5516..................
So no ideas today huh...........
You are accessing snack[3], which is out of bounds of the array. You allocated only three elements, not four.
You are accessing snack[3], which is out of bounds of the array. You allocated only three elements, not four.



Damn, that was the dumbest thing I've ever done................thank you very much you are a God to me, I missed it like a hundred times. Staring at this code so damn long I guess I over looked the simple...........


Thank you again, you are my hero!!!
Topic archived. No new replies allowed.