my strcpy funcution!
-
char *my_strcpy(char *p1, char *p2) { if (p2 == NULL ) return p1; if (p1 == NULL) return 0; else { char *pp1 = p1; char *pp2 = p2; while (p2 != '\0') { *p1++ = *p2++; } *pp1 = '\0'; } return p1; } Is there something wrong in my function and why? Thanks in advantage
-
char *my_strcpy(char *p1, char *p2) { if (p2 == NULL ) return p1; if (p1 == NULL) return 0; else { char *pp1 = p1; char *pp2 = p2; while (p2 != '\0') { *p1++ = *p2++; } *pp1 = '\0'; } return p1; } Is there something wrong in my function and why? Thanks in advantage
-
char *my_strcpy(char *p1, char *p2) { if (p2 == NULL ) return p1; if (p1 == NULL) return 0; else { char *pp1 = p1; char *pp2 = p2; while (p2 != '\0') { *p1++ = *p2++; } *pp1 = '\0'; } return p1; } Is there something wrong in my function and why? Thanks in advantage
wbgxx wrote:
Is there something wrong in my function
Have you tested it? What makes you think there's something wrong with it?
-
wbgxx wrote:
Is there something wrong in my function
Have you tested it? What makes you think there's something wrong with it?
-
wbgxx wrote:
sorry,I can not test it ,can you tell me how to do it ?
Well, how do you intend to become a developper ?? Anyway, you have a couple of choices. - simulate it on paper (run it by hand, line by line with a pencil and some paper). - run it in a debugger (Visual Studio has a good one). Max.
Watched code never compiles.
-
Pretty much as shown here http://www.space.unibe.ch/comp_doc/c_manual/C/FUNCTIONS/strcpy.html[^]
-
char *my_strcpy(char *p1, char *p2) { if (p2 == NULL ) return p1; if (p1 == NULL) return 0; else { char *pp1 = p1; char *pp2 = p2; while (p2 != '\0') { *p1++ = *p2++; } *pp1 = '\0'; } return p1; } Is there something wrong in my function and why? Thanks in advantage
Well try stepping through it with your eyes (aka reading) one line at a time. Then when you get to the line that reads
*p1++ = *p2++;
ask yourself what is the purpose of pointer
pp1
. This looks a bit like the sort of confusion that arises from not using useful variable names.It's time for a new signature.
-
char *my_strcpy(char *p1, char *p2) { if (p2 == NULL ) return p1; if (p1 == NULL) return 0; else { char *pp1 = p1; char *pp2 = p2; while (p2 != '\0') { *p1++ = *p2++; } *pp1 = '\0'; } return p1; } Is there something wrong in my function and why? Thanks in advantage
The first two
if()
tests are not necessary. Also,pp2
is not necessary.wbgxx wrote:
while (p2 != '\0')
This will not terminate like you want it to. Richard hints at the last piece of the puzzle.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"Man who follows car will be exhausted." - Confucius