簡體   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