I read a (seemingly good) tutorial on how to "return arrays from functions". This is one of the methods described: "Have the caller allocate an array and use that within the function":
Code:
char *func(char *buf);
main (int argc, char *argv) {
char buf[25];
char *str = func(buf);
printf("%s\n", str);
printf("%s\n", buf);
}
char *func(char *buf) {
strcpy(buf, "abcdefghifklmnopqrstuvwxy");
return buf;
}
However, isn't this unnecessary?
1. Returning the pointer from the *func() function isn't necessary. The functions inserts the string into the allocated array, using the pointer passed to it. Why returning anything here? Just for the look of it?
2. When doing it this way, couldn't you just use void methods to populate the arrays?
3. If returning isn't necessary, why should the caller create two arrays (buf and str)? Couldn't you just do like this:
Code:
main (int argc, char *argv) {
char buf[25];
func(buf);
printf("%s\n", buf);
return 0;
}
char *func(char buf[25]) {
strcpy(buf, "abcdefghifklmnopqrstuvwxy");
}