• 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;
    }

  • 相关阅读:
    [BZOJ1006]神奇的国度
    配置ubuntu18.04
    数据库的基本操作
    关于排序的算法——桶排序
    关于TCP/IP协议的记录
    laravel学习历程
    装箱问题
    01背包
    数字三角形
    统计单词的个数
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14831855.html
Copyright © 2020-2023  润新知