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)从该处开始打印

具体如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值