简体   繁体   中英

C: copy a char *pointer to another

i have some trouble with a simple copy function:

void string_copy(char *from, char *to) {

    while ((*to++ = *from++) != '\0')
        ;
}

It takes two pointers to strings as parameters, it looks ok but when i try it i have this error:

Segmentation fault: 11

This is the complete code:

#include <stdio.h>

void string_copy(char *from, char *to);

int main() {
    char *from = "Hallo world!";
    char *to;
    string_copy(from,to);
    return 0;
}

Thank you all

Your problem is with the destination of your copy: it's a char* that has not been initialized. When you try copying a C string into it, you get undefined behavior.

You need to initialize the pointer

char *to = malloc(100);

or make it an array of characters instead:

char to[100];

If you decide to go with malloc , you need to call free(to) once you are done with the copied string.

You need to allocate memory for to . Something like:

char *to = malloc(strlen(from) + 1);

Don't forget to free the allocated memory with a free(to) call when it is no longer needed.

In this program

#include <stdio.h>

void string_copy(char *from, char *to);

int main() {
    char *from = "Hallo world!";
    char *to;
    string_copy(from,to);
    return 0;
}

pointer to has indeterminate value. As result the program has undefined behavior.

Also function string_copy has a wrong interface. It says that it does not guarantees that string pointed to by from will not be changed.

Also there is a common convention in C that functions that deal with strings usually return pointer to the destination string.

The function should be declared like

char * string_copy( const char *from, char *to );
^^^^^^              ^^^^^

Its definition could look like

char * string_copy( const char *from, char *to ) 
{
    for ( char *p = to; ( *p = *from ) != '\0'; ++p, ++from )
    {
        ;
    }

    return to;
}

And the program could look like

#include <stdio.h>
#include <string.h>
#include >stdlib.h>

char * string_copy( const char *from, char *to );

int main( void ) 
{
    char *from = "Hallo world!";
    char *to;

    to = malloc( strlen( from ) + 1 );

    puts( string_copy( from, to ) );

    free( to );

    return 0;
}

char * string_copy( const char *from, char *to ) 
{
    for ( char *p = to; ( *p = *from ) != '\0'; ++p, ++from )
    {
        ;
    }

    return to;
}

Take into account that you may not use pointer to declared like

    char *from = "Hallo world!";
    char *to   = "Hello everybody!";

in the function because string literals are immutable.

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