help with Char pointers (for formatted dates)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tbonifie
    New Member
    • Nov 2007
    • 2

    #1

    help with Char pointers (for formatted dates)

    Hello -

    I'm re-learning some programming to use at work (haven't done C in 11 years and am learning C++)...

    I'm returning a pointer from a function and when it's returned, the target char array has some extra garbage characters at the end.

    So here's the function I've written (with much stripped away):

    pMydate points to a 'char MyOtherArray[17]' outside of the function...

    [code=c]char* asciDate(char* pMydate)
    {
    char myarray[17];
    char* pMyarray;

    // some code here that puts the characters in the string...

    pMyarray = myarray;
    strncpy(pMydate , pMyarray, 17);
    return pMydate;
    }[/code]

    When I get back to the code that calls this function, MyOtherArray holds exactly what I expect. pMydate, however, which is pointing to MyOtherArray, shows the 17 characters I expect, then 2 additional garbage characters.

    If I try to output pMydate to stdio or a file, it includes the garbage. (i.e. cout << pMydate;)

    Why are 2 garbage characters showing up where the pointer is pointing?

    Platform = WinXP
    Using Microsoft Visual C++ (Visual Studio 8)
    Last edited by Ganon11; Nov 21 '07, 06:32 PM. Reason: Please use the [CODE] tags provided, rather than [INDENT] tags.
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    How is a regular character array different from a C string? Remember that a C string requires that it be terminated with a NUL ('\0') character. If you have 17 letters, to form a C string, you need the 18th NUL character.

    Comment

    • tbonifie
      New Member
      • Nov 2007
      • 2

      #3
      Thanks, figured it was a stupid newbie question!!!

      Works like a charm.

      Regards,

      Travis

      Comment

      Working...