简体   繁体   English

复制字符串而不使用strcpy

[英]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等效的代码,以下是对其使用的算法的高级描述:

  1. Copy the character in *source to *destination *source的字符复制到*destination
  2. If the character that was just copied was the null terminator, exit. 如果刚刚复制的字符是空终止符,请退出。
  3. Otherwise, increment the pointer to source , and increment the pointer to destination . 否则,将指针增加到source ,并将指针增加到destination
  4. Go to step 1. 转到步骤1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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