Write a function to create a copy of a string with the prototype below. (C Language)
char * strcpy (const char *);
The function should dynamically allocate the necessary memory for the new string. You can do that with
char * newstr = (char *) malloc(sizeof(char) * (strlen(str)+1));
assuming str is your input string. Think though how you would copy the characters of the string, and don't forget about the end of string character.
#include <stdio.h> #include <stdlib.h> char *strcpy(const char *); int main() { char *s = strcpy("Hello"); printf("%s\n", s); free(s); return 0; } char *strcpy(const char *str) { int len = 0, index = 0; char *result; while (str[len]) ++len; result = (char *) malloc(sizeof(char) * (len + 1)); while (str[index]) { result[index] = str[index]; ++index; } result[index] = '\0'; return result; }
Get Answers For Free
Most questions answered within 1 hours.