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');

}
2

2 Answers 2

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Technically, a string literal isn't const (6.4.5(6)), it's just undefined behaviour if one tries to modify it.
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';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.