• strcpy函数学习


    strcpy的功能如下:

    原型声明:char *strcpy(char* dest, const char *src);
    头文件:#include <string.h> 和 #include <stdio.h>
    功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间
    说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
    返回指向dest的指针。
    例子1:
    #include<stdio.h>
    #include<string.h>
    
    int  main(void)
    {
        char* str1="hello1";
        char* str2="hello2";
        printf("str1=%s 
    ",str1);
        printf("str2=%s 
    ",str2);
        strcpy(str1,str2);
        printf("str1=%s 
    ",str1);
        printf("str2=%s 
    ",str2);
        return 0;
    }

    运行结果:

    len@DESKTOP-BDP8J2M /cygdrive/e/c_study
    $ gcc strcpy.c -o strcpy

    len@DESKTOP-BDP8J2M /cygdrive/e/c_study
    $ ./strcpy.exe
    str1=hello1
    str2=hello2
    Segmentation fault (核心已转储)

    例子2:

    #include<stdio.h>
    #include<string.h>
    
    int  main(void)
    {
        char str1[]="hello1";
        char* str2="hello2";
        printf("str1=%s 
    ",str1);
        printf("str2=%s 
    ",str2);
        strcpy(str1,str2);
        printf("str1=%s 
    ",str1);
        printf("str2=%s 
    ",str2);
        return 0;
    }

    运行结果:

    len@DESKTOP-BDP8J2M /cygdrive/e/c_study
    $ gcc strcpy.c -o strcpy

    len@DESKTOP-BDP8J2M /cygdrive/e/c_study
    $ ./strcpy.exe
    str1=hello1
    str2=hello2
    str1=hello2
    str2=hello2

    例子1和例子2的结论和随笔"静态内存"遇到的问题一样,strcpy的dest实参不可以是char*,必须是char[],即要是预先分配的字符内存空间。

     
  • 相关阅读:
    OpenResty
    Jmeter
    kubernetes 中部署 metrics-server
    Jenkins 灰度
    socat管理haproxy以及haproxy调优
    代码质量测试工具SonarQube安装配置
    Jenkins+主从+Pipeline+Webhook
    xtrabackup 实现MySQL数据库备份
    idea Error:java: Compilation failed: internal java compiler error
    使用TableSnapshotInputFormat读取Hbase快照数据
  • 原文地址:https://www.cnblogs.com/jason207489550/p/6662942.html
Copyright © 2020-2023  润新知