Mail Archives: djgpp/2000/08/05/10:00:21
djgpp AT delorie DOT com wrote:
>I have this program that converts a string to date. Most of the time it
>does it correctly but some times it gives wrong values. I run the
>program from a DOS box (i can only run it from a DOS box). That
>subroutine the main program calls it about 2000 times per execution and
>sometimes it reports wrong values. Can someone help me?
>The input string is declared as "hmeromhnia[8]" in the main program and
>as char *string here.
>And the format of hmeromhnia[8] is xxyyzzzz where xx is the date yy the
>month and zzzz the year.
>Here is the program:
>void date_str(char *string, int *day, int *month, int *year)
>{
>int i;
>char c, c1[2], c2[2], c3[4];
>for(i = 0;i < 2;i++)
> {
> c = string[i];
> c1[i] = c;
> }
[SNIP]
This is a classic mistake, and I'm sure everyone of us has
made it a some point: you provided c1 to take 2 chars, so
you declared it as char c1[2]. What you always have to do is
take the number of chars you want and add 1 to that. The
additional char is for the \0-char you need at the end of
your string. That is a char that equals 0.
Why? Because the compiler and your program need to know,
when to finish reading a string you provide. They do that by
looking for the \0 character. If they can't find that magic
NULL, they are gonna keep on reading. At some point they
will find a byte with a value of NULL, but that can be way
behind the end of your string.
->Declare all your char[] one larger than you thought you'd
need.
->Set that last char in the array to 0.
char c1[3];
c1[2]=0;
..
--
Manni
"Life would be much easier if I had the source code."
- Raw text -