我从过去的试卷中得到了以下问题:
考虑以下源代码:
using namespace std;
int main()
{
char dest[20];
printf( "%s\n", altcopy( dest, "demo" ) );
printf( "%s\n", altcopy( dest, "demo2" ) );
printf( "%s\n", altcopy( dest, "longer" ) );
printf( "%s\n", altcopy( dest, "even longer" ) );
printf( "%s\n", altcopy( dest, "and a really long string" ) );
}
为名为 altcopy() 的函数提供一个实现,它使用指针算法将 C 类型字符串的替代字符复制到目标(即第一个、第三个、第五个等字符)。您的答案不得使用 [] 运算符来访问数组索引。上面的代码将输出以下内容:
dm
dm2
lne
ee ogr
adaral ogsrn
我尝试过如下:
using namespace std;
char* altcopy (char* dest, const char* str)
{
char* p = dest;
const char* q = str;
for ( int n=0; n<=20; n++ )
{
*p = *q;
p++;
q++;
q++;
}
return dest;
}
int main()
{
char dest[20];
printf( "%s\n", altcopy( dest, "demo" ) );
printf( "%s\n", altcopy( dest, "demo2" ) );
printf( "%s\n", altcopy( dest, "longer" ) );
printf( "%s\n", altcopy( dest, "even longer" ) );
printf( "%s\n", altcopy( dest, "and a really long string" ) );
}
结果是:
dm
dm2lne
lne
ee ogradaral ogsrn
adaral ogsrn
我不确定为什么它碰巧在某些输出上有重复的下一条语句结果,而不是按照问题要求的那样执行。这里有什么帮助吗?
最佳答案
您的函数至少是无效的,因为它使用了魔数(Magic Number) 20。
该函数应该类似于标准函数 strcpy
,即它必须复制源字符串,直到遇到终止零。
这里是一个简单的功能实现
#include <iostream>
char * altcopy( char *dest, const char *str )
{
char *p = dest;
while ( *p++ = *str++ )
{
if ( *str ) ++str;
}
return dest;
}
int main()
{
char dest[20];
std::cout << altcopy( dest, "demo" ) << std::endl;
std::cout << altcopy( dest, "demo2" ) << std::endl;
std::cout << altcopy( dest, "longer" ) << std::endl;
std::cout << altcopy( dest, "even longer" ) << std::endl;
std::cout << altcopy( dest, "and a really long string" ) << std::endl;
return 0;
}
输出是
dm
dm2
lne
ee ogr
adaral ogsrn
尽情享受吧!:)
关于c++ - 指针运算,按引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23941253/