program taken out of book won't run
The following code was taken out of a book but gets a seg fault:
Code:
//time.h |
Try this:
Code:
void time::set_time (const char hhmm[4]) |
Hi,
&tod24[2] means take address of the 3th character of the string and give that to the atol function. '\0' is the string terminator, so you cut off the string at the 3th character. |
“&tod24[2]” is equivalent to “tod24 + 2” (but some people like the awkward form ;) ). If this still does not make sense to you, try this code:
Code:
#include <stdio.h> |
I understand the programming in this (what it does) but why would I want to do that in this program? Why is it giving me a seg fault?
|
Cause it was written by an amateur. And back then the compilers were less strict.
|
Quote:
Code:
#include <stdio.h> Quote:
Code:
int main() { PS. And yeah, similarly to what NevemTeve has said, based on the code, I would recommend you stop reading this book and use it for something useful like starting a fire place. |
Quote:
Any comprehensive book suggestions on c++? |
Quote:
|
Quote:
If you provided h:m format (where h is a digit for hours, and m one or more digits for minutes), starting on the third character would convert the minutes. The second part converts the hours, but assumes that the conversion will terminate when it reaches a non digit character (the ":" in my example format). Unfortunately, it won't work correctly if you provide "h" or "hh" where "h" is a digit of the hours. This is because the third character would be at or beyond the end of the string - and hopefully only causes a segfault, because you are accessing data beyond the end of a buffer. Looking at the entire program, I suspect the book is fairly old. It should be using snprintf to prevent formatting past the buffer, and the parameter should include the buffer length... |
Quote:
|
Quote:
One way to avoid this is for set_time() to have its own character array. eg: Code:
void time::set_time(char *tod24) |
Quote:
Code:
void time::set_time(const char *tod24); |
All times are GMT -5. The time now is 08:12 PM. |