簡體   English   中英

C - 復制沒有庫的字符串 function

[英]C - Copy a String without a library function

我想創建一個 function ,它接受一個字符串文字和一個數組,並將字符串文字的字符復制到數組中。 您能否告訴我以下代碼中的問題是什么? 此代碼的 output 只是帶有一些空格(“D”)的大寫 D,所以我認為以某種方式訪問了隨機位置。

#include <stdio.h>

int main(void)
{
    //Function Prototypes:
    void CopyAString(const char * s1, char s2[]);
    
    // Initialize the string literal str1 and an array s2 of size 12.
    const char *str1 = "Hello World";
    char s2[12];
    // In the function i pass the address of str1 and the array s2.
    CopyAString( &str1, s2 );

    for (int i = 0; i <= 12; i++){
        printf("%c", s2[i]);
    }

}

void CopyAString(const char * s1, char s2[])
{
    const char * p1 = s1;
    int index = 0;

    while (*p1 != '\0') {
        s2[index] = *p1;
        index++;
        p1++;
    }
}

你的程序有兩個錯誤:

第一的

您的 function CopyAString不會在字符串末尾寫入'\0'字符。 這意味着字符串s2[]沒有'\0'字符,您將無法將s2[]傳遞給printf()之類的函數或其他期望“輸入”字符串以'\0'結尾的函數'\0' .

但是,在您的程序中,這不是問題,因為for循環需要一個固定長度的字符串。

第二

在您的程序中,以下問題更為重要:

您將&str作為第一個參數傳遞給CopyAString而不是str

這意味着s1CopyAString的第一個參數)不指向"Hello world"的字符'H' ,而是指向存儲在變量str中的值的第一個字節......

請注意,變量str是一個指針:它不存儲“值”(此處為字符串"Hello world" ),但它存儲值的地址!

If the string "Hello world" is stored in the RAM at address 0x20 44 00 40 (this means: 0x40004420 on an x86 or ARM computer or 0x20440040 on a PowerPC), the variable str will contain the value 0x20 44 00 40 .

s1[0]將是0x20 (這是空格字符)。 s1[1]將是0x44 (即'D' )...

對於初學者,您應該像這樣聲明 function

char * CopyAString( char *s1, const char *s2 );

類似於標准字符串 function strcpy

在這個 function 通話中

CopyAString( &str1, s2 );

表達式&str1的類型為const char **並產生指針str1的地址,但 function 需要類型為const char *的參數表達式,它指向字符串的第一個元素(字符串文字)。

在 function 中,您不會復制終止零字符

while (*p1 != '\0') {
    s2[index] = *p1;
    index++;
    p1++;
}

所以目標字符數組一般不會包含字符串。

function 可以通過以下方式定義

char * CopyAString( char *s1, const char *s2 )
{
    for ( char *p = s1; ( *p++ = *s2++ ); );

    return s1;
}

在調用未定義行為的條件中,在 main 而不是這個 for 循環中使用幻數 12

for (int i = 0; i <= 12; i++){
    printf("%c", s2[i]);
}

最好寫

for ( char *p = s2; *p != '\0'; ++p ){
    printf("%c", *p );
} 
putchar( '\n' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM