I've been playing around a bit and attempting to create a char method which accepts strings (char arrays), does something with them, and then returns a string. However, I'm running into more trouble than I seem to be able to figure my way out of. And most internet articles are of little help, because most of the code examples I find produce the same warnings that I get, or even other ones.
Code:
char textadd(char *, char *); // string method
main() {
char str1[10];
char str2[10];
strcpy(str1, "Sometext");
strcpy(str2, "Moretext");
textadd(str1, str2); <----------- send the to char arrays/strings to the textadd() method
OR
printf("%c\n", textadd(str1, str2));
}
char textadd(char *s1, char *s2) {
int newsize = (strlen(s1)+strlen(s2)+1); // - the size the of the two strings combined.
char ns1[newsize]; // - Create a new string with the new size.
strcpy(ns1, s1); // - Copy the contents of s1 into the new string.
strcat(ns1, s2); // - Run strcat() on the new string (which contains s1) and s2.
printf("New string: %s\n", ns1); <--- PRINTS OUT THE COMBINED STRINGS FINE
printf("%p\n", &ns1); <--- PRINTS OUT THE ADDRESS FINE
// Then I try to return the string:
return ns1;
}
When I try returning the string as above, I get the following warning:
methods.c:71: warning: return makes integer from pointer without a cast
methods.c:71: warning: function returns address of local variable
So, I cannot return a char array from a char method?
And - I cannot return the address, because the variable contaning the new string is local.
If I do
instead, the returned value is an integer (83). Not very helpful, though I am curious as to where it comes from.
So basically what I'm wondering about is how to do this when involving arrays. With int or double variables it's easy, but I need a lot of work on getting used to the way strings/arrays are handled in C.