I'm trying to make my own strcpy. A version of strcpy that will allow this,
PHP Code:
[code]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *content1;
char *content2 = "hello world";
printf("%s\n", content2);
strcpy(content1, content2);
printf("%s\n", content1);
return 0;
}
[/code]
Of course the app crashes upon strcpy attempt because content1 doesn't have memory allocated in it. It's why I wrote this function.
PHP Code:
[code]
void my_strcpy(char *dest, const char *src) {
dest = (char *) malloc(sizeof(strlen(src)));
while(*src) {
*dest++ = *src++;
}
*dest = '\0';
}
[/code]
where I was hoping my_strcpy(content1, content2); would work as expected. But no. content1 is NULL;
How do I retain the allocated memory in my_strcpy's dest parameter?
One solution is to make my_strcpy a non-void function.
PHP Code:
[code]
char *my_strcpy(char *dest, const char *src) {
dest = (char *) malloc(sizeof(strlen(src)));
char *destcpy = dest;
while(*src) {
*dest++ = *src++;
}
*dest = '\0';
return destcpy;
}
[/code]
But I would have to use content1 = my_strcpy(content1, content2);, and not as simple as my_strcpy(content1, content2); like strcpy does.
How do I pass-by-reference and retain allocated memory?