首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

这个函数有有关问题吗

2012-04-24 
这个函数有问题吗?我看到网上有这样一道题目:函数如下void test1(){ char a[10] char* str1 012345678

这个函数有问题吗?
我看到网上有这样一道题目:
函数如下
void test1()
{
 char a[10];
 char* str1 = "0123456789";
 strcpy( a, str1 );
}
====================
解答如下:

字符串str1需要11个字节才能存放下(包括末尾的’\0’),而string只有10个字节的空间,strcpy会导致数组越界;
========================================================================================================



可是我认为:a是数组,并不要求最后一个字符是‘\0'结束符。而且strcpy并不会复制'\0'给对象a。

所以这个函数是没有问题的。

对吗?请指教




[解决办法]
char * strcpy ( char * destination, const char * source );
Copy string
Copies the C string pointed by source into the array pointed by destination, including the terminating null character.

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
[解决办法]
strcpy是要复制'\0'给a的。而且C语言没有数组防越界检查,strcpy根本就不会管给它的数组有多大。
[解决办法]

探讨

引用:
a是数组,并不要求最后一个字符是‘\0'结束符

char 类型的数组也需要一个结束符,同样是‘\0’,所以数组为10时只能存9个数

热点排行