0

I'm testing the function void strcpy(char *s, char *t) I've just learned in K&R (page 106) but my codes (shown below) don't seem to work. Please help. Thanks a lot.

PS: I've changed the name of the function to strcpy1 to differentiate it from the built-in one in the standard library.

#include<stdio.h>
void strcpy1(char *s, char *t);

int main() {
char *m = "Love is beautiful";
char *n;
strcpy1(n, m);
printf("%s", n);
}

void strcpy1(char *s, char *t)
{
    while (*s++ = *t++)
            ;
}
O'Neil
  • 3,790
  • 4
  • 16
  • 30
Nien Van
  • 9
  • 1
  • 3
    You did not allocate memory for `n`, try `char n[100];` or `char* n = malloc(100);` – mnistic Apr 22 '18 at 20:31
  • Thanks, mnistic. I got it now. How can I vote up your answer? This is the first time I've asked a question on stackoverflow. – Nien Van Apr 22 '18 at 20:37
  • @NienVan People aren't supposed to put answers in comments... welcome to StackOverflow :) I have created an Answer that you can upvote and accept. Also, thanks for posting a clear question with a complete code example – M.M Apr 22 '18 at 20:40
  • it's also a super duplicate. so a comment + a duplicate closure is just as well. – Jean-François Fabre Apr 22 '18 at 20:42
  • @Jean-FrançoisFabre Disagree with the duplicate ; there is no `scanf` in this question , it is hardly an "exact duplicate" although the answer is similar. – M.M Apr 22 '18 at 20:44
  • same root cause. A better duplicate can probably be found, but we're not creating 1 question by system call which is passed uninitialized pointers. – Jean-François Fabre Apr 22 '18 at 20:45
  • see? strcpy _and_ uninitialized pointer duplicate (linked to a canonical) – Jean-François Fabre Apr 22 '18 at 20:46
  • 1
    char *strcpy1(char *dest, const char *src); -learn proporly. function return the char * for possible use in the assingments or functions calls. src should be const. It is very important to learn how properly use **const** – 0___________ Apr 22 '18 at 20:49
  • Calling it `strcpy1` rather than `strcpy` (which is the name of a standard function) is a good start -- but all identifiers whose names start with `str` (or `mem`, or `wcs`) followed by a lowercase letter are reserved. `str_cpy()` is ok. – Keith Thompson Apr 23 '18 at 00:33

1 Answers1

1

You did not allocate memory for n, try char n[100]; or char* n = malloc(100);.

M.M
  • 138,810
  • 21
  • 208
  • 365