<address id="ousso"></address>
<form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
  1. C語言

    C語言的strcpy()和strncpy()函數

    時間:2025-06-04 16:04:16 C語言 我要投稿
    • 相關推薦

    C語言的strcpy()和strncpy()函數

      對于C語言來說,什么是strcpy()和strncpy()函數呢?這對于想要學習C語言的小伙伴來說,是必須要搞懂的事情,下面是小編為大家搜集整理出來的有關于C語言的strcpy()和strncpy()函數,一起看看吧!

      strcpy()函數

      strcpy() 函數用來復制字符串,其原型為:

       char *strcpy(char *dest, const char *src);

      【參數】dest 為目標字符串指針,src 為源字符串指針。

      注意:src 和 dest 所指的內存區域不能重疊,且 dest 必須有足夠的空間放置 src 所包含的字符串(包含結束符NULL)。

      【返回值】成功執行后返回目標數組指針 dest。

      strcpy() 把src所指的由NULL結束的字符串復制到dest 所指的數組中,返回指向 dest 字符串的起始地址。

      注意:如果參數 dest 所指的內存空間不夠大,可能會造成緩沖溢出(buffer Overflow)的錯誤情況,在編寫程序時請特別留意,或者用strncpy()來取代。

      示例:

    <form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    /* copy1.c -- strcpy() demo */
     
    #include
     
    #include // declares strcpy()
     
    #define SIZE 40
     
    #define LIM 5
     
    char * s_gets(char * st, int n);
     
    int main(void)
     
    {
     
    char qwords[LIM][SIZE];
     
    char temp[SIZE];
     
    int i = 0;
     
    printf("Enter %d words beginning with q: ", LIM);
     
    while (i < LIM && s_gets(temp, SIZE))
     
    {
     
    if (temp[0] != 'q')
     
    printf("%s doesn't begin with q! ", temp);
     
    else
     
    {
     
    strcpy(qwords[i], temp);
     
    i++;
     
    }
     
    }
     
    puts("Here are the words accepted:");
     
    for (i = 0; i < LIM; i++)
     
    puts(qwords[i]);
     
    return 0;
     
    }
     
    char * s_gets(char * st, int n)
     
    {
     
    char * ret_val;
     
    int i = 0;
     
    ret_val = fgets(st, n, stdin);
     
    if (ret_val)
     
    {
     
    while (st[i] != ' ' && st[i] != '
    <address id="ousso"></address>
    1. 日日做夜狠狠爱欧美黑人