面试题--字符串拷贝函数

题目:     

已知strcpy函数的原型是:       

  char * strcpy(char * strDest,const char * strSrc);     

1.不调用库函数,实现strcpy函数。     

2.解释为什么要返回char *。


参考答案:

1)不调用C++/C的字符串库函数,请编写函数 strcpy
char *strcpy(char *strDest, const char *strSrc)
{

    assert((strDest!=NULL) && (strSrc !=NULL));    // 2分

    char *address = strDest;                                          // 2分
    while( (*strDest++ = * strSrc++) != '\0' )         // 2分
              NULL ;
    return address ;                                                  // 2分
}


(2)strcpy能把strSrc的内容复制到strDest,为什么还要char * 类型的返回值?
答:为了实现链式表达式。                                              // 2分
例如       int length = strlen( strcpy( strDest, “hello world”) );

错误的做法:
[1](A)不检查指针的有效性,说明答题者不注重代码的健壮性。
    (B)检查指针的有效性时使用((!strDest)||(!strSrc))或(!(strDest&& strSrc)),说明答题者对C语言中类型的隐式转换没有深刻认识。在本例中char *转换为bool即是类型隐式转换,这种功能虽然灵活,但更多的是导致出错概率增大和维护成本升高。所以C++专门增加了bool、true、false 三个关键字以提供更安全的条件表达式。
    (C)检查指针的有效性时使用((strDest==0)||(strSrc==0)),说明答题者不知道使用常量的好处。直接使用字面常量(如本例中的 0)会减少程序的可维护性。0虽然简单,但程序中可能出现很多处对指针的检查,万一出现笔误,编译器不能发现,生成的程序内含逻辑错误,很难排除。而使用 NULL代替0,如果出现拼写错误,编译器就会检查出来。
[2](A)return new string("Invalid argument(s)");,说明答题者根本不知道返回值的用途,并且他对内存泄漏也没有警惕心。从函数中返回函数体内分配的内存是十分危险的做法,他把释放内存的义务抛给不知情的调用者,绝大多数情况下,调用者不会释放内存,这导致内存泄漏。
    (B)return 0;,说明答题者没有掌握异常机制。调用者有可能忘记检查返回值,调用者还可能无法检查返回值(见后面的链式表达式)。妄想让返回值肩负返回正确值和异常值的双重功能,其结果往往是两种功能都失效。应该以抛出异常来代替返回值,这样可以减轻调用者的负担、使错误不会被忽略、增强程序的可维护性。
[4](A)循环写成while (*strDest++=*strSrc++);,同[1](B)。
    (B)循环写成while (*strSrc!='\0') *strDest++=*strSrc++;,说明答题者对边界条件的检查不力。循环体结束后,strDest字符串的末尾没有正确地加上'\0'。

 对于第一个错误,可能很多人会写成这样

if((strDest==NULL) || (strSrc ==NULL))   return NULL;    // 2分

其实这样也是不太妥的,因为这之后程序会继续运行,而用断言assert就会中断程序。

关于assert的用法,下一节总结。

assert() 函数用法
assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:
#include <assert.h>
void assert( int expression );
assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,
然后通过调用 abort 来终止程序运行。

另外,对于strcpy()函数看看linux标准中时如何写的,如下:

linux下的标准strcpy函数的写法:(tring.c在/usr/src/linux-.../lib/string.c下面)
/**
 * strcpy - Copy a %NUL terminated string
 * @dest: Where to copy the string to
 * @src: Where to copy the string from
 */
char *strcpy(char *dest, const char *src)
{
char *tmp = dest;
while ((*dest++ = *src++) != '\0')
/* nothing */;
return tmp;
}

附:linux下string.c中一些函数的源码:

/**
 * strncpy - Copy a length-limited, %NUL-terminated string
 * @dest: Where to copy the string to
 * @src: Where to copy the string from
 * @count: The maximum number of bytes to copy
 *
 * The result is not %NUL-terminated if the source exceeds
 * @count bytes.
 *
 * In the case where the length of @src is less than  that  of
 * count, the remainder of @dest will be padded with %NUL.
 *
 */
char *strncpy(char *dest, const char *src, size_t count)
{
char *tmp = dest;


while (count) {
if ((*tmp = *src) != 0)
src++;
tmp++;
count--;
}
return dest;
}
/**
 * strcmp - Compare two strings
 * @cs: One string
 * @ct: Another string
 */
int strcmp(const char *cs, const char *ct)
{
unsigned char c1, c2;


while (1) {
c1 = *cs++;
c2 = *ct++;
if (c1 != c2)
return c1 < c2 ? -1 : 1;
if (!c1)
break;
}
return 0;
}


/**
 * strlen - Find the length of a string
 * @s: The string to be sized
 */
size_t strlen(const char *s)
{
const char *sc;


for (sc = s; *sc != '\0'; ++sc)
/* nothing */;
return sc - s;
}




/**
 * memset - Fill a region of memory with the given value
 * @s: Pointer to the start of the area.
 * @c: The byte to fill the area with
 * @count: The size of the area.
 *
 * Do not use memset() to access IO space, use memset_io() instead.
 */
void *memset(void *s, int c, size_t count)
{
char *xs = s;


while (count--)
*xs++ = c;
return s;
}


/**
 * memcpy - Copy one area of memory to another
 * @dest: Where to copy to
 * @src: Where to copy from
 * @count: The size of the area.
 *
 * You should not use this function to access IO space, use memcpy_toio()
 * or memcpy_fromio() instead.
 */
void *memcpy(void *dest, const void *src, size_t count)
{
char *tmp = dest;
const char *s = src;


while (count--)
*tmp++ = *s++;
return dest;
}


C/C++面试之算法系列--几个典型的内存拷贝字符串函数实现 写一个函数,完成内存之间的拷贝。[考虑问题是否全面,是否考虑内存重叠问题] 返回void *支持链式操作,参数类型是void *以支持任意类型的指针,输入参数加上const修饰,最好加上assert对输入输出指针进行非NULL判断 void* memcpy( void *dest, const void *src, size_t count ) { char* pdest = static_cast<char*>( dest ); const char* psrc = static_cast<const char*>( src ); // 依次从前拷贝,目的地址覆盖了源地址的数,此时从后往前拷贝 if( (pdest>psrc) && (pdest<(psrc+count))) //能考虑到这种情况就行了 { for( size_t i=count-1; i!=-1; --i ) pdest[i] = psrc[i]; } else { for( size_t i=0; i<count; ++i ) pdest[i] = psrc[i]; } return dest; } int main( void ) { char str[] = "0123456789"; memcpy( str+1, str+0, 9 ); cout << str << endl; memcpy( str, str+5, 5 ); cout << str << endl; system( "Pause" ); return 0; // 0012345678 // 4567845678 } strcmp(): Int simple_strcmp (const char *s1, const char *s2) { int ret; while ((ret = *(unsigned char *) s1 - *(unsigned char *) s2++) == 0 && *s1++); return ret; } memcmp(): int simple_memcmp (const char *s1, const char *s2, size_t n) { int ret = 0; while (n--&& (ret = *(unsigned char *) s1++ - *(unsigned char *) s2++) == 0); return ret; } strcmp只判断s1的‘/0’,没有长度的控制;memcmp有长度参数n的控制 memcpy(): char *simple_memcpy (char *dst, const char *src, size_t n) { char *ret = dst; while (n--) *dst++ = *src++; return ret; } 直接的内存之间的copy,不处理内存重叠的情况。 strcpy(): char *simple_strcpy (char *dst, const char *src) { char *ret = dst; while ((*dst++ = *src++) != '\0'); //相当简约,一句话即搞定 return ret; } 与memcpy区别就是对'\0'作为结束符 strncpy(): char *simple_strncpy (char *dst, const char *src, size_t n) { char *ret = dst; while (n--) { if ((*dst++ = *src++) == '\0') { while (n--) *dst++ = '\0'; return ret; } } return ret; } n和‘\0'都作为结束的控制符。如果n过大,则后面全补'\0'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值