0
点赞
收藏
分享

微信扫一扫

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 条评论