简体   繁体   中英

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?

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:

  1. Copy the character in *source to *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 .
  4. Go to step 1.

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