A
arnuld
I have created my own implementation of strcpy library function. I would
like to have comments for improvements:
/* My version of "strcpy - a C Library Function */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
enum { ARRSIZE = 101 };
char* my_strcpy( char*, char* );
int main( int argc, char** argv )
{
char* pc;
char arr_in[ARRSIZE];
char arr_out[ARRSIZE];
memset( arr_in, '\0', ARRSIZE );
memset( arr_out, '\0', ARRSIZE );
if( 2 != argc )
{
perror("USAGE: ./exec \" your input \"\n");
exit( EXIT_FAILURE );
}
else
{
strcpy( arr_in , argv[1] );
}
pc = my_strcpy( arr_out, arr_in );
while( *pc )
{
printf("*pc = %c\n", *pc++);
}
return EXIT_SUCCESS;
}
char* my_strcpy( char* arr_out, char* arr_in )
{
char* pc;
pc = arr_out;
while( (*arr_out++ = *arr_in++) ) ;
return pc;
}
=============== OUTPUT ======================
[arnuld@dune ztest]$ gcc -ansi -pedantic -Wall -Wextra check_STRCPY.c
[arnuld@dune ztest]$ ./a.out like
*pc = l
*pc = i
*pc = k
*pc = e
[arnuld@dune ztest]$
It works fine without troubles. Now if you change the last return call in
my_strcpy from "return pc" to return "return arr_out", then while loop in
main() will not print anything at all. I really did not understand it.
Using thr array name will give a pointer to its 1st element but int htis
case it is giving a pointer to its last element. Why ? Thats why I
introduced the extra "char* pc" in first place.
like to have comments for improvements:
/* My version of "strcpy - a C Library Function */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
enum { ARRSIZE = 101 };
char* my_strcpy( char*, char* );
int main( int argc, char** argv )
{
char* pc;
char arr_in[ARRSIZE];
char arr_out[ARRSIZE];
memset( arr_in, '\0', ARRSIZE );
memset( arr_out, '\0', ARRSIZE );
if( 2 != argc )
{
perror("USAGE: ./exec \" your input \"\n");
exit( EXIT_FAILURE );
}
else
{
strcpy( arr_in , argv[1] );
}
pc = my_strcpy( arr_out, arr_in );
while( *pc )
{
printf("*pc = %c\n", *pc++);
}
return EXIT_SUCCESS;
}
char* my_strcpy( char* arr_out, char* arr_in )
{
char* pc;
pc = arr_out;
while( (*arr_out++ = *arr_in++) ) ;
return pc;
}
=============== OUTPUT ======================
[arnuld@dune ztest]$ gcc -ansi -pedantic -Wall -Wextra check_STRCPY.c
[arnuld@dune ztest]$ ./a.out like
*pc = l
*pc = i
*pc = k
*pc = e
[arnuld@dune ztest]$
It works fine without troubles. Now if you change the last return call in
my_strcpy from "return pc" to return "return arr_out", then while loop in
main() will not print anything at all. I really did not understand it.
Using thr array name will give a pointer to its 1st element but int htis
case it is giving a pointer to its last element. Why ? Thats why I
introduced the extra "char* pc" in first place.