#include <stdio.h>
#include <stdlib.h>
int main() {
char *str, *temp;
str = malloc(sizeof(char) * 100);
fgets(str, 100, stdin);
temp = str;
printf("%s", str);
return 0;
}
Is this valid code to copy one string to another without using strcpy()
function?
You are merely copying the starting address of str
to temp
. This means that any changes to temp
will be reflected in str
as well, since they point to the same memory. It does not truly emulate strcpy(dest, src)
, which creates a separate copy of the null-terminated string pointed to by src
starting at the memory location pointed to by dest
.
So, to answer your question as asked: no.
If your intent is to avoid the O(n) running time of strcpy
, that's also something you can't really do.
If you're required by a programming assignment or exercise to create code functionally equivalent to strcpy
, here is a high-level description of the algorithm it uses:
*source
to *destination
source
, and increment the pointer to destination
.
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.