Provide the prototype for a function called my_str_n_cpy () that accepts two poi
ID: 3930788 • Letter: P
Question
Provide the prototype for a function called my_str_n_cpy () that accepts two pointers to characters, which represent addresses to the beginning of the destination buffer/array and the source buffer array, and an integer n. The function copies a total of n characters from the source buffer into the destination buffer. If the null character is encountered in the source buffer before n characters have been copied, then the destination character should be filled in with the null character until n is reached. The function must return a pointer to the beginning of the destination buffer.Explanation / Answer
//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] != '')
{
dest_size++;
i++;
}
//copy from source to destination
for (i = 0; i <n; i++,dest_size++)
{
if (source[i] != '')
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]="";
//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] != '')
{
dest_size++;
i++;
}
//copy from source to destination
for (i = 0; i <n; i++,dest_size++)
{
if (source[i] != '')
destination[dest_size] = source[i];
else
break;
}
//return destination pointer
return destination;
}
Sample Output:
my_s
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.