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

C-Style Character String

I want to connect two C-style character strings and store the result in a dynamic char array.

int main()
{
  char word1[] = "hello";
  char word2[] = "haha";
  auto ptr = new char[20];
  strcpy(ptr,strcat(word1,word2));
  cout<<ptr<<endl;
  return 0;
}

The compiler says there is a "segmentation fault" at the statement strcpy(ptr,strcat(word1,word2));. Why does the compiler say that?

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

>Solution :

Like this

strcpy(ptr, word1);
strcat(ptr, word2);

You need to use ptr for both operations, the copy and the concatenation.

In your version strcat(word1,word2) tries to concatenate word2after the end of word1. But there is no accessible memory there, so you get a segmentation fault.

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