I have been doing well with the string functions I've been making recently. So then, I made my 3rd string function that is basically like strcpy()
:
#include <stdio.h>
#include <string.h>
const char *copy_str(const char *str);
int main() {
char name[256];
printf("What's your name? "); scanf("%255s", name);
char result[256] = copy_str(name);
printf("Hello, %s.\n", result);
}
const char *copy_str(const char *str) {
return str;
}
I didn't try using the strcpy()
function itself in the function I made, because I'm not really familiar with it. Then I got an error:
copy_str.c:9:10: error: array initializer must be an initializer list or string literal
char result[256] = copy_str(name);
^
I fixed it this way:
int main() {
char name[256];
printf("What's your name? "); scanf("%255s", name);
char result[256];
strcpy(name, result);
printf("Hello, %s.\n", result);
}
But then the output went like this:
What's your name? builderman
Hello, .
No string for some reason. Even if you typed in a different string, it would be the same result.
Q: Why did strcpy()
ruin my string? What ways can I improve my function?