I'm trying to write strcpy on my own using pointers and I get an error during runtime.
void str_cpy(char **destination, const char *source) {
// char *s1 = *destination;
while (*source != '\0') {
**destination++ = *source++; //Get an error here
}
**destination = '\0';
}
I call the function as follows:
char *str = NULL;
str_cpy(&str, "String");
Is it not OK?
Thanks!
strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.
Parameter of strcpy() in C In C to use the strcpy() function, we must pass two strings of the same length as a parameter of the function. The two strings will be the source string and the destination string so that the content of the source string can be copied to the destination string.
strcpy() — Copy Strings The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string. No length checking is performed. You should not use a literal string for a string1 value, although string2 may be a literal string.
strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string. h header file and in C++ it is present in cstring header file. Syntax: char* strcpy(char* dest, const char* src);
No, it's not okay. Why? Because str
is a NULL
pointer. It's pointing to nothing. When you try to write values into it, where will they go? It's not pointing to any allocated memory!
You first have to allocate memory for str
. You can do:
char *str = malloc(strlen("String") + 1); // + 1 for the '\0' character at the end of C-style strings
Or you can do:
char str[256]; // make str large enough to hold 256 chars. Note that this is not as safe as the above version!
Also, destination
should be a single pointer, not a double pointer. Well, it's not technically wrong to use a double pointer, it's just unnecessary.
Optionally, you can allocate the memory in the str_cpy
function, like so:
void str_cpy(char **destination, const char *source) {
*destination = malloc(strlen(source) + 1);
// ... continue as normal
For simplicity's sake, this can be done in one line in a function.
void mystrcpy(char *dest, const char *src) {
while (*dest++ = *src++);
}
This being said, you do need to allocate memory for dest
beforehand using malloc
or just simply by having a character array like char dest[256]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With