zoukankan      html  css  js  c++  java
  • c语言中字符串的复制

    c语言中字符串的复制。

    1、

    #include <stdio.h>
    
    char* str_copy(char *d, const char *s)  //函数的返回值为指向char型的指针型, 形参为两个指向char型的指针。 
    {
        char *t = d;   // 指针t等于指针d,指针d为指向字符串第一个字符的指针,因此t为指向字符串第一个字符的指针, 
        
        while(*d++ = *s++)  // 其实单纯赋值的话,本句就已经解决 , d和s都为指向数组第一个元素的指针,依次后移、赋值、知道空字符,赋值表达式的结果为左操作数的值和结果。 
            ;
        return t;  // t为指向d的第一个字符的指针,因此t的行为和字符串(数组)本身的行为一样。 
    }
    
    int main(void)
    {
        char str[128] = "ABCD";  // str初始值 
        char tmp[128];
        
        printf("str: %s
    ", str);
        
        printf("tmp = ", tmp); scanf("%s", tmp);  // tmp tmp ??????
        
        str_copy(str, tmp);  //传入两个字符串(数组)。 
        
        printf("str: %s
    ", str);  // 显示复制后的结果 
        
        return 0;
    }

    2、不正确的字符串复制 ???

    #include <stdio.h>
    
    char* str_copy(char *d, const char *s)
    {
        char *t = d;
        
        while(*d++ = *s++)
            ;
        return t;    
    } 
    
    int main(void)
    {
        char *ptr = "ABCD";    //此处使用指针实现字符串 
        char tmp[128];
        
        printf("ptr: %s
    ", ptr);
        
        printf("tmp = ", tmp); scanf("%s", tmp);
        
        str_copy(ptr, tmp);//  改写了字符串字面量 ?? 可能会写入非空的内存空间。???
        
        printf("ptr : %s
    ", ptr);
        
        return 0;
    }

  • 相关阅读:
    cnpm镜像安装
    wxParse解析html
    C++回调函数
    QT源码分析:QTcpServer
    QT实现支持加密的Sqlite数据库引擎
    VS2013+OpenCV3.4.2编译
    Android Tcp操作
    使用Delphi开发linux应用
    QT5.10+MinGW+OpenCV3.4.2编译
    C++ ActiveX开发的问题讨论
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14831855.html
Copyright © 2011-2022 走看看