Home > Software design >  std::strcpy and std::strcat with a std::string argument
std::strcpy and std::strcat with a std::string argument

Time:06-02

This is from C Primer 5th edition. What do they mean by "the size of largeStr". largeStr is an instance of std::string so they have dynamic sizes?

Also I don't think the code compiles:

#include <string>
#include <cstring>

int main()
{
    std::string s("test");
    const char ca1[] = "apple";
    std::strcpy(s, ca1);
}

Am I missing something?

CodePudding user response:

strcpy and strcat only operate on C strings. The passage is confusing because it describes but does not explicitly show a manually-sized C string. In order for the second snippet to compile, largeStr must be a different variable from the one in the first snippet:

char largeStr[100];

// disastrous if we miscalculated the size of largeStr
strcpy(largeStr, ca1);        // copies ca1 into largeStr
strcat(largeStr, " ");        // adds a space at the end of largeStr
strcat(largeStr, ca2);        // concatenates ca2 onto largeStr

As described in the second paragraph, largeStr here is an array. Arrays have fixed sizes decided at compile time, so we're forced to pick some arbitrary size like 100 that we expect to be large enough to hold the result. However, this approach is "fraught with potential for serious error" because strcpy and strcat don't enforce the size limit of 100.

Also I don't think the code compiles...

As above, change s to an array and it will compile.

#include <cstring>

int main()
{
    char s[100] = "test";
    const char ca1[] = "apple";
    std::strcpy(s, ca1);
}

Notice that I didn't write char s[] = "test";. It's important to reserve extra space for "apple" since it's longer than "test".

CodePudding user response:

You are missing the

char largeStr[100];

or similar the book doesn't mention.

What you should do is forget about strcpy and strcat and C-style strings real quick. Just remember how to make c std::string out of them and never look back.

  •  Tags:  
  • c
  • Related