c++ - Pointer Arithmetic, Pass by Reference -
i got following question past exam paper:
consider following source code:
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 long string" ) ); }
provide implementation function called altcopy() uses pointer arithmetic copy alternate characters of c-type string destination (i.e. first, third, fifth etc character). answer must not use [] operator access array index. above code output following:
dm dm2 lne ee ogr adaral ogsrn
and have attempted follows:
using namespace std; char* altcopy (char* dest, const char* str) { char* p = dest; const char* q = str; ( 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 long string" ) ); }
and results are:
dm dm2lne lne ee ogradaral ogsrn adaral ogsrn
i'm not sure why happened have duplicate of next statement result on output instead of performing question asked for. here?
your function invalid @ least because uses magic number 20. function should similar standard function strcpy
has copy source string until terminating 0 encountered.
here simple function realization
#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 long string" ) << std::endl; return 0; }
the output is
dm dm2 lne ee ogr adaral ogsrn
enjoy!:)
Comments
Post a Comment