[英]Copy string without strcpy
#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? 这是不使用strcpy()
函数将一个字符串复制到另一个字符串的有效代码吗?
You are merely copying the starting address of str
to temp
. 您只是将str
的起始地址复制到temp
。 This means that any changes to temp
will be reflected in str
as well, since they point to the same memory. 这意味着对temp
任何更改也将反映在str
中,因为它们指向同一内存。 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
. 它并没有真正模拟strcpy(dest, src)
,后者会从dest
指向的内存位置开始创建src
指向的以null终止的字符串的单独副本 。
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. 如果您要避免strcpy
的O(n)运行时间,那也是您实际上无法做到的事情。
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: 如果需要进行编程作业或练习来创建功能上与strcpy
等效的代码,以下是对其使用的算法的高级描述:
*source
to *destination
将*source
的字符复制到*destination
source
, and increment the pointer to destination
. 否则,将指针增加到source
,并将指针增加到destination
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.