How to copy a string in C?

Asked

Viewed 64 times

1

The following method I found on the internet, serves to create a string copy.:

char* bin_copy_string(const char* begin, const char* end) {
    char* result;
    result = malloc(end - begin);
    if (result) {   // result is a valid pointer, and not a null pointer
        char* p = result;
        while (begin != end) {
            *(p++) = *(begin++);
        }
    }
    return result;
}

My question is on the line char* p = result; , why the new pointer p is modifying the string result but in the end returns result? You couldn’t just do *(result++) = *(begin++); ?

2 answers

5


He is not modifying the string result because result is not a string, is a variable and you may notice that nowhere this variable is modified.

It changes the variable p increasing the pointer to go walking character to character of the object string. Same goes for pointer begin in sync.

It does not alter result because this variable points to the beginning of the object string. When finished you want to return to the beginning of the object and not to the end, so you can’t touch it.

You can change the way you are thinking and see what happens. You will return a value pointing to the terminator of the string So when you use it, there’s nothing useful there.

This function is prone to failure if you don’t use it properly, so it might not be a good idea to use it.

1

You can use the strdup of C:

#include <stdlib.h>

int main() {
  char *s="...........";
  char *s_copy=strdup(s); // this copies the string
  // ...
}
  • strdup() is not part of the standard library C is a peculiarity POSIX. It would be better to use the AP example with strcpy().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.