0

The following code shows a segmentation error. How to solve the problem? What is the problem with the code?

#include <stdio.h>

void stcp (char *, char *);

int
main ()
{
  char *s = "This is first string";
  char *t = "string to be copied";
  stcp (s, t);
  printf ("%s", s);
  getch ();
}

void
stcp (char *s, char *t)
{
  while ((*s++ = *t++) != '\0');

}
Arka
  • 837
  • 4
  • 8
Ashikur Rahman
  • 145
  • 1
  • 3
  • 10

2 Answers2

1

A string literal is constby default. To make it un-const, you must make it an array:

char s[] = "this is my string";
char t[] = "another string";
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
0
#include <stdio.h>

void stcp (char *s, char *t);

int main (void)
{
  int i;
  char s[] = "This is first string";
  char t[] = "string to be copied        ";
  stcp (s, t);
  printf ("%s\n", s);
  printf ("%s\n", t);
  //getch ();
  return 0;
}

void stcp (char *s, char *t)
{
  int i;
  for (i=0;  (s[i]  != '\0')  &&  (t[i] != '\0') ;i++) {
    printf("%c  %c\n",s[i],t[i]);
    s[i] = t[i];
  }
  s[i] ='\0';
}
fhtuft
  • 966
  • 5
  • 8