Provide the prototype for a function called mystrncpy that
Solution
//function prototype
char *my_str_n_cpy (char *destination, char *source, int n);
//function defition
/*
The function my_str_n_cpy that takes two pointers destination, source
and integer n value and copies the source to destination for given size
*/
char *my_str_n_cpy (char *destination, char *source, int n)
{
int i = 0;
int source_size = 0;
int dest_size = 0;
//get size of source
while (source[i] != NULL)
{
source_size++;
i++;
}
i=0;
//get size of destination
while (destination[i] != \'\\0\')
{
dest_size++;
i++;
}
//copy from source to destination
for (i = 0; i <n; i++,dest_size++)
{
if (source[i] != \'\\0\')
destination[dest_size] = source[i];
else
break;
}
//return destination pointer
return destination;
}
------------------------------------------------------------------------------------------------------------------
//Test program
#include<stdio.h>
#include<conio.h>
//function prototype
char *my_str_n_cpy (char *destination, char *source, int n);
int main()
{
//intialize two c-strings
char source[50]=\"my_string\";
char dest[50]=\"\\0\";
//calling fucntion
char *result=my_str_n_cpy(dest,source,4);
int i=0;
//print result to console
while (result[i] != NULL)
{
printf(\"%c\", result[i]);
i++;
}
getch();
return 0;
}
/*
The function my_str_n_cpy that takes two pointers destination, source
and integer n value and copies the source to destination for given size
*/
char *my_str_n_cpy (char *destination, char *source, int n)
{
int i = 0;
int source_size = 0;
int dest_size = 0;
//get size of source
while (source[i] != NULL)
{
source_size++;
i++;
}
i=0;
//get size of destination
while (destination[i] != \'\\0\')
{
dest_size++;
i++;
}
//copy from source to destination
for (i = 0; i <n; i++,dest_size++)
{
if (source[i] != \'\\0\')
destination[dest_size] = source[i];
else
break;
}
//return destination pointer
return destination;
}
Sample Output:
my_s

