帮助解决结构中的分段错误
我在调试代码时遇到问题。我有一个结构和一个 函数计算以 HH:MM:SS 格式输入的时差。 我的代码是:
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 << ans;
MyTime *timeDiff;
timeDiff->hours = ans / hourConv;
timeDiff->minutes = ans % hourConv / minConv;
timeDiff->seconds = ans % hourConv % minConv;
return timeDiff;
}
我相信问题出在倒数第二行: timeDiff->秒= ans%hourConv%minConv;
自从我评论该行以来, 我没有收到分段错误错误。但我不明白为什么 该行无效。任何帮助将不胜感激。谢谢!
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 << ans;
MyTime *timeDiff;
timeDiff->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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码包含:
您已创建一个 MyTime 指针,但未分配任何内容。此时 timeDiff 为空。
Your code contains:
You have created a MyTime pointer but not allocated anything. timeDiff is null at this point.
您尝试使用以下代码访问未分配的内存:
尽管您可以通过使用 new 手动分配代码来解决此问题,如下所示:
我强烈建议更改您的函数以按值返回 MyStruct 作为堆栈分配的变量。我还建议将参数作为传递常量引用:
You're trying to access unallocated memory with the following code:
Although you could solve this by manually allocating the code using new, as:
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:
还有一点要注意的是:在这种情况下使用 OOP。它将使您的代码更具可读性。您最终将有更多时间来考虑未初始化的内存。
除此之外,区分时差和“绝对”时间值是个好主意。您可以添加两个时间差异,但不能添加两个“日历”值。
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.
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.