0

I'm trying to implement my own strcat function for exercise 5-3 from K&Rs the C programming language. Here is what I have, which causes a seg fault.

#include <stdio.h>

void cat(char *st, char *end)
{
  while(*st++);
  while(*st++ = *end++);
}


int main()
{
  char *start = "str";
  char *end = "ing!";

  cat(start, end);
  printf("start = %s\n", start);
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
CS Student
  • 1,613
  • 6
  • 24
  • 40
  • You need to review what a string is. – Fiddling Bits Jul 21 '14 at 17:45
  • @FiddlingBits Okay, the C answer book has an almost identical solution to this problem as mine. Could you point me in the right direction? – CS Student Jul 21 '14 at 17:50
  • 1
    Start by reviewing the duplicate question answers. Make `start` a `char` array with enough room to concatenate `end` to its contents. – Fiddling Bits Jul 21 '14 at 17:52
  • Check out page 104 of the K&R book, specifically in the middle of the page where it says, "There is an important difference between these definitions". You're getting an error because your *start pointer is pointing to an area of memory that is not able to be changed. As Fiddling Bits mentioned above, you need to change this into an Array instead of a pointer. Also, make sure that your array is large enough to hold the contents of both strings including the Null character. Your *start pointer is pointing to a location that is not large enough to accommodate both strings. – Adam Bak Aug 11 '18 at 17:10

0 Answers0