C/C++数组边界与赋值

声明:   char buf[5]; 则元素为 a[0] a[1] a[2] a[3] a[4]
       a[5]  不属于buf数组 该数组可以最多存放a[0] a[1] a[2] a[3] 这4个字符, 而因为字符数组的第5个a[4]字符用于/0

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{
    char str[5];
    char c='d';

    strcpy(str,"hello"); //string copy (include '/0')

    printf("d:%d c:%c str:%s /n", c,c, str );

    if(c == '/0')
        printf("c == '//0' /n");
    else
        printf("c != '//0' /n");

    return 0;
}

[root@localhost cpp]# ./a
d:0    c:     str:hello
c == '/0'                       //可见strcpy把str[5]也就是char c的内存空间填入了/0

正确的做法是


[root@localhost cpp]# cat a.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{
    char str[5];
    char c='d';

     strncpy(str,"hello",sizeof(str)-1); //str copy (不包含'/0', 也就是到达源串尾也不自动添加/0)
                         //
    str[4]='/0';
    printf("d:%d c:%c str:%s /n", c,c, str );

    if(c == '/0')
        printf("c == '//0' /n");
    else
        printf("c != '//0' /n");

    return 0;
}


[root@localhost cpp]# ./a
d:100     c:d    str:hell
c != '/0'


不加str[x]='/0'
[root@localhost cpp]# cat a.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{
    char str[6];
    char c='d';

    strncpy(str,"hello",sizeof(str)-1); //str copy ( '/0')
                         //
    //str[5]='/0';            不添加/0会引起下面的乱码错误, 随后的变量c的内容也未可预料
    printf("d:%d c:%c str:%s /n", c,c, str );

    if(c == '/0')
        printf("c == '//0' /n");
    else
        printf("c != '//0' /n");

    return 0;
}


[root@localhost cpp]# ./a
d:100 c:d str:helloSd0瓯繄瓯?jO狘SO堦笨,jO
c != '/0';
;;;;;;;;;;;;;;;总结;;;;;;;;;
使用 strcnpy函数时正确做法:
char array[80];
const char *src = "sdjfksdfjksdf";
;;;;第一种方式
strcnpy(array, src, sizeof(array));
array[sizeof(array) - 1] = '/0'; // 为避免 src 长度超过80(包括'/0') 时array数组末尾没有加‘/0’.导致缓冲区溢出。
;;;;;;;;;第二种方式;;;;;;;;
memset(array, 0, sizeof(array));
strncpy(array, src, sizeof(array) -1);  // 这样,由于memset 把 array 添0,所以保证array[sizeof(array) -1] = '/0';
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
当src 长度小于80 时 没有问题。注意,strncpy()不会自动添加 '/0';
除非 你能保证 src的长度不会超过array的长度,这时可以直接用 strcpy(array, src);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值