Homegrown strncpy implementation C programming Objectives Practice imlpementing
ID: 3805411 • Letter: H
Question
Homegrown strncpy implementation C programming
Objectives
Practice imlpementing an algorithm
Practice working with strings in C
In this lab, you are going to create your own implementation of the strncpy function from the C Library. Recall that the strncpy copies a given number of character elements from a source character array (string) into a destination character array.
You will write a function my_strncpy that replicates the behavior of the built-in strncpy function. Your main method will test this function out with different source and destination arrays.
Remember that a character array can be represented as a character pointer to the first element, as is done in the prototype for strncpy and our own my_strncpy function.
NOTE: Please don't use any functions from string.h in this lab.
Requirements:
Your my_strncpy function will have the following prototype: char *my_strncpy(char *dest, char *source, int n)
Notice that the function returns a pointer to a char. Like the built-in function, you will simply return dest.
You will use a loop to assign the first n elements of dest to the first n elements of source.
HINT: Even though source and dest are passed in as pointers and not arrays, you can still use the subscript [ i ] notation to access the ith element.
You could also use pointer arithmetic to increment source and dest to point to their next element on each iteration.
Remember that the null character must be appended to dest at index n
Your function does not need to do any safety checks to make sure n is less than the length of dest.
Test your function by inserting your my_strncpy function into the appropriate place in the following program.
Explanation / Answer
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( " source string = %s", source ) ;
printf ( " target string = %s", target ) ;
strncpy ( target, source, 5 ) ;
printf ( " target string after strcpy( ) = %s", target ) ;
return 0;
}
OUTPUT:
source string = fresh2refresh
target string =
target string after strncpy( ) = fresh
C STRING FUNCTIONS:
String functions
Description
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( " source string = %s", source ) ;
printf ( " target string = %s", target ) ;
strncpy ( target, source, 5 ) ;
printf ( " target string after strcpy( ) = %s", target ) ;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.