strcpy()函數用法及其詳解

strcpy()函數用法及其詳解

含義:

C 庫函數 char *strcpy(char *dest, const char *src) 把 src 所指向的字符串複製到 dest。

需要注意的是如果目標數組 dest 不夠大,而源字符串的長度又太長,可能會造成緩衝溢出的情況。

聲明:

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

參數:

  • dest – 指向用於存儲複製內容的目標數組。
  • src – 要複製的字符串。

返回值:

該函數返回一個指向最終的目標字符串 dest 的指針。

案例:
要求用戶輸入以q開頭的單詞,該程序把輸入拷貝到一個臨時數組中,如果第一個單詞的開頭是q,程序調用strcpy()函數把整個字符從臨時數組temp拷貝到目標數組qword中

/*
 * @Author: Your name
 * @Date:   2020-02-24 14:35:13
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-02-24 14:48:42
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 40
#define LIM 5
char *s_gets(char *,int);
int main()
{
    char qword[LIM][SIZE];
    char temp[SIZE];
    int i = 0;
    printf("enter %d words beginning with q:\n",LIM);
    while(i<5&&s_gets(temp,SIZE))
    {
        if(temp[0]!='q')
        {
            printf("%s doesn't begin with q.\n",temp);
        }
        else
        {
            strcpy(qword[i],temp);
            i++;
        }
    }
    puts("Here are the words accepts:");
    for(int i = 0;i<5;i++)
    {
        puts(qword[i]);
    }
    getchar();
    return 0;
}
char *s_gets(char *str,int n)
{
    char * rev;
    rev = fgets(str,n,stdin);
    int i = 0;
    if(rev)
    {
        while(str[i]!='\0'&&str[i]!='\n')
        {
            i++;
        }
        if(str[i]=='\n')
        {
            str[i] = '\0';
        }
        else
        {
            while(getchar()!='\n')
            {
                continue;
            }
        }
    }
    return rev;
}

下面這兩句代碼等效:

if(temp[0]!='q');
if(strncmp(temp,"q",1)!=0);

而下面的語句是錯誤案例:

char *str;
strcpy(str,"The C of Tranquility");

strcpy()"The C of Tranquility"拷貝到str指向的地址上,但是str未被初始化,所以該字符串可能被拷貝到任意的地方。

strcpy()的其它屬性:

  1. strcpy()的返回類型是char *,該函數返回的是一個字符的地址。
  2. 第一個參數不必指向數組的開始,這個特性可用於拷貝數組的一部分。

下面這個程序演示了將一個字符串拷貝到另一個字符數組的指定位置:

/*
 * @Author: Your name
 * @Date:   2020-02-24 14:35:13
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-02-24 15:26:57
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define WORDS "beast"
#define SIZE 40
int main()
{
    const char * orig = WORDS;
    char copy[SIZE] = "Be the best that you can be.";
    char * ps;
    puts(orig);
    puts(copy);
    ps = strcpy(copy+7,orig);//ps==&copy[7],第八個元素的地址。
    puts(copy);
    puts(ps);
    getchar();
    return 0;
}

下面是該程序的輸出:

beast
Be the best that you can be.
Be the beast
beast
注意:
strcpy()把源字符的空字符也拷貝進去
所以空字符覆蓋了copy數組中that的第一個t
由於第一個參數是copy+7,所以ps指向copy中的第8個元素,因此puts(ps)從該處開始打印

具體如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章