Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::strcpy and std::strcat with a std::string argument

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <string>
#include <cstring>

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

Am I missing something?

>Solution :

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".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading