Ripple dans 5 ans

Comment

Author: Admin | 2025-04-28

I am having trouble debugging my code. I have a struct and a function to compute the time difference entered in HH:MM:SS format. My code is: const int hourConv = 3600; // used to get total hours from total seconds const int minConv = 60; struct MyTime { int hours, minutes, seconds; }; MyTime *determineElapsedTime(const MyTime *time1, const MyTime *time2) { long timeOneSec = time1->hours*hourConv + time1->minutes*minConv + time1->seconds; long timeTwoSec = time2->hours*hourConv + time2->minutes*minConv + time2->seconds; long ans = timeTwoSec - timeOneSec; cout hours = ans / hourConv; timeDiff->minutes = ans % hourConv / minConv; timeDiff->seconds = ans % hourConv % minConv; return timeDiff; } I believe the problem to be with the 2nd to last line: timeDiff->seconds = ans%hourConv%minConv;since when i comment that line out, I do not get a segmentation fault error. But I don't understand why that line is invalid. Any help would be appreciated. Thanks! Dan McGrath42k11 gold badges103 silver badges130 bronze badges asked Nov 10, 2009 at 5:05 1 Your code contains:MyTime *timeDiff;timDiff->hours = ...You have created a MyTime pointer but not allocated anything. timeDiff is null at this point. answered Nov 10, 2009 at 5:10 Jim GarrisonJim Garrison86.8k20 gold badges160 silver badges193 bronze badges 6 You're trying to access unallocated memory with the following code:MyTime *timeDiff;timeDiff->hours = ans / hourConv;Although you could solve this by manually allocating the code using new, as:MyTime *timeDiff = new MyTime;timeDiff->hours = ans / hourConv;I'd highly recommend changing your function to return the MyStruct by value, as a stack-allocated variable. I'd also suggest taking the arguments as pass-by-const reference:MyTime determineElapsedTime(MyTime const &time1, MyTime const &time2){ long timeOneSec = time1.hours*hourConv + time1.minutes*minConv + time1.seconds; long timeTwoSec = time2.hours*hourConv + time2.minutes*minConv + time2.seconds; long ans = timeTwoSec - timeOneSec; cout answered Nov 10, 2009 at 5:42 Jon BenedictoJon Benedicto10.6k3 gold badges29 silver badges30 bronze badges 1 Just one other remark: use OOP in this case. It will make your code so much more readable. You'll end up with more time to think about uninitialized memory.struct MyTime { int hours, minutes, seconds; int timeInSeconds() const { return hours*3600 + minutes*60 + seconds; } // the difference, in seconds int operator-( const MyTime other ) const { return timeInSeconds() - other.timeInSeconds(); } void subtract( int seconds ) { seconds -= seconds; while( seconds = 0 ); }}; Next to that, it's a good idea to differentiate between time-differences and 'absolute' time values. You can add two time diffs, but you cannot add two 'calendar' values. answered Nov 10, 2009 at 6:06 xtoflxtofl41.5k12 gold badges109 silver badges202 bronze badges

Add Comment