简体   繁体   中英

Can I emulate strcpy using malloc?

I'm trying to make a strcpy function from scratch for a class. While I could do it with a for loop and copy the individual characters, I think I could just make a swap using malloc and pointers to make it more efficient. Here's my code, but I've been getting a lot of confusing errors.

void notStrcpy(char s1[], char s2[]) { //copies string s1 into s2
char *s3 = (char *) malloc(strlen(s1)); //s3 is now an alias of s1
s2 = *s3;} //dereference s3 to dump s1 into s2

Why is this happening, and is there any way to make this code work the way I intended it?

You cannot do that: strcpy expects both chunks of memory to be ready - one for reading the string, and the other one for writing the string. Both addresses are expected to have enough memory for the actual content of a null-terminated C string.

On the other hand, malloc gives you a third chunk of memory (you need to allocate strlen(s)+1 , but that's a completely different story). String copy algorithm has no use for that chunk of memory. On top of that, assigning parameters of a function has no effect on the values passed into your function, so s2 = *s3 is not doing what you think it should be doing.

Long story short, while ((*s1++ = *s2++)); is your simplest strcpy implementation.

Note: malloc could come in handy in an implementation of string duplication function, eg strdup . If you decide to give it a try, don't forget to allocate space for null terminator.

@dasblinkenlight Thank you. My new code is as follows:

void totallyNotstrcpy(char s1[], char s2[]) {
int x = 0;
while (x < strlen(s1)+1) {
    s2[x] = s1[x];
    x++;
}
}

As a quick side question, how does your code snippet work? Doesn't the while loop need a condition?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM