Create a new string before using strcpy?

This is a discussion on Create a new string before using strcpy? within the C++ Programming forums, part of the General Programming Boards category; A little chunk of code: ClassGFX already has a char *Name;. Code: ClassGFX::ClassGFX(const char *NewName, int Num) { char TempString[50]="GFX/"; ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    125

    Question Create a new string before using strcpy?

    A little chunk of code:
    ClassGFX already has a char *Name;.
    Code:
    ClassGFX::ClassGFX(const char *NewName, int Num)
    {
      char TempString[50]="GFX/";
      Name=new char[strlen(NewName)];
      strcpy(Name, NewName);
      strcat(TempString,NewName);
    }
    Is the command to create a new string for Name necessary, or will strcpy take care of that? Also, is that TempString correct, or do I have to add a /o after it to end it? (btw, I'm going to do some more with the TempString later)

  2. #2
    Has a Masters in B.S.
    Join Date
    Aug 2001
    Posts
    2,267
    >Is the command to create a new string for Name necessary, or will strcpy take care of that?

    you must do it! strcp() expects there to be enough space!

    >Also, is that TempString correct, or do I have to add a /o after it to end it?

    when you initialize it that '/0' is added automatically, most of the std library functions that act on strings add the '\0' themselves but explicitly adding if your not sure is not bad practice.
    ADVISORY: This users posts are rated CP-MA, for Mature Audiences only.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Is the command to create a new string for Name necessary, or will strcpy take care of that?
    Yes.

    > Name=new char[strlen(NewName)];

    This should be:
    Name=new char[strlen(NewName)+1];

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    125
    OK, I got it.
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 07:02 AM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  3. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 10:19 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21