Simple pointer issue
Aug 17, 2017 at 7:13pm UTC
when i try to read the carbon n the hydrogen, it appears a lot of error messages.in a previous program I did the same but instead of new int was new int[8], is there any difference? and why is not reading properly?
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
#include <iostream>
using namespace std;
typedef struct {
int * carbon;
int * hydrogen;
}Hidrocarbon;
int main(){
Hidrocarbon* mass = new Hidrocarbon;
mass->carbon = new int ;
mass->hydrogen = new int ;
cin >> mass->carbon;
cin >> mass->hydrogen;
cout<< (mass->carbon)*12 + mass->hydrogen<<endl;
delete carbon;
delete hydrogen;
delete mass
return 0;
}
Last edited on Aug 17, 2017 at 7:14pm UTC
Aug 17, 2017 at 8:28pm UTC
The pointer needs to be dereferenced to access the integer which it points to.
Also the
delete
s don't match the
new
s.
1 2 3 4 5 6 7 8 9 10 11 12
Hidrocarbon* mass = new Hidrocarbon;
mass->carbon = new int ;
mass->hydrogen = new int ;
cin >> *mass->carbon;
cin >> *mass->hydrogen;
cout<< (*mass->carbon)*12 + *mass->hydrogen<<endl;
delete mass->carbon;
delete mass->hydrogen;
delete mass;
Though it has to be said, the pointers don't seem useful here.
Last edited on Aug 17, 2017 at 8:28pm UTC
Topic archived. No new replies allowed.