C 标准库—— string.h

1. strlen()(与 sizeof())

\0退出,它返回的字符串的长度是真实的长度。

strlen(str) + 1 == sizeof(str);

二者最为重要的区别在于:

  • strlen 是函数调用(function call);
  • sizeof 编译期确定(compile time);

2. strcpy()

把从 src 地址开始且含有 ‘\0’ 结束符的字符串复制到以 dest 开始的地址空间。

char* strcpy(char* des,const char* source)
{
    char* r=des;

    assert((des != NULL) && (source != NULL));

    while((*des++ = *source++)!='\0');

    return r;
}

这就要求 dst 的长度不少于 src 的长度;

3. strcpy vs memcpy

  • memcpy() 是用来拷贝内存的,
    • 头文件:<string.h>(malloc 所在的头文件则是:<stdlib.h>)
  • strcpy() 是用来拷贝内容的,遇到’\0’就结束
    • 头文件:<string.h>

4. 指定长度字符串的拷贝:strncpy

char* dst = NULL;
dst = (char*)malloc(sizeof(src));
strncpy(dst, src, sizeof(src));
    // strncpy(dst, src, strlen(src)+1);

5. warning: incompatible implicit declaration of built-in function ‘memcpy’

为 memset/memcpy 等函数引入头文件, string.h/memory.h

char cache[250][250];
memset(cache, -1, sizeof(cache));
                                    // 比 for 循环更为高效
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值