繁体   English   中英

C:将char *指针复制到另一个

[英]C: copy a char *pointer to another

我在使用简单的复制功能时遇到了一些麻烦:

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

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

它需要两个指向字符串作为参数的指针,它看起来不错但是当我尝试它时我有这个错误:

Segmentation fault: 11

这是完整的代码:

#include <stdio.h>

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

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

谢谢你们

您的问题在于您的副本的目的地:它是尚未初始化的char* 当您尝试将C字符串复制到其中时,您将获得未定义的行为。

您需要初始化指针

char *to = malloc(100);

或者使它成为一个字符数组:

char to[100];

如果您决定使用malloc ,则需要在完成复制的字符串后调用free(to)

您需要为分配内存to 就像是:

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

不要忘记在不再需要时通过free(to)呼叫释放已分配的内存。

在这个计划中

#include <stdio.h>

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

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

指针to具有不确定的值。 结果该程序具有未定义的行为。

函数string_copy也有错误的接口。 它表示它不保证from指向的字符串不会被更改。

在C中还有一个共同的约定,处理字符串的函数通常会返回指向目标字符串的指针。

该函数应该声明为

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

它的定义可能看起来像

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

    return to;
}

程序可能看起来像

#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;
}

考虑到你可能不使用指针to声明如下

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

在函数中,因为字符串文字是不可变的。

暂无
暂无

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

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