0

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?

Eric Yan
  • 31
  • 3

1 Answers1

2

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.

john
  • 85,011
  • 4
  • 57
  • 81