I thought I could return an array like I do in Java, but I think there is no way to declare a char function in C.
Asked
Active
Viewed 66 times
-2
-
1You can return a pointer to memory which you have allocated dynamically. Then index it as if it is an array. Or you can return a pointer to a static array. But you must not return a pointer to an array which is local to the function. – Weather Vane May 26 '22 at 21:51
-
So there is no way to declare a int[] function, right? – Luan C. Redmann May 26 '22 at 21:54
-
No, but you can have a `char *function`, as for example the library function `strcpy()`. Or an `int *function` and so on. – Weather Vane May 26 '22 at 21:55
-
1In Java, all objects are accessed through pointers. The pointers are just hidden from you, and not directly accessible. So you just have to get used to the fact that C doesn't hide the pointers from you. Returning an array in both Java and C means returning a pointer, only the syntax is different. – user3386109 May 26 '22 at 21:56
-
1If you really want to, I think you can put an array in a `struct` and return the `struct`, but I would consider that bad practice (and inefficient since a copy of the array will be made). If you're learning C, you're going to have to learn how to work with pointers, no way around it. – yano May 26 '22 at 21:58
-
1C is not Java, so do not assume you can do the same as you can in Java. It is a very different language, and both have their own quirks. – Cheatah May 26 '22 at 22:14
-
@yano It's not necessarily bad practice to return a struct, or to return a struct that encapsulates an array. See [What does impossibility to return arrays actually mean in C?](https://stackoverflow.com/questions/50808782) – Steve Summit May 26 '22 at 22:30
-
@SteveSummit interesting read on your answer, but I've never created a `struct` for the express purpose of containing an array so I can return an array from a function, nor do I recall seeing it (or many functions returning `struct`s at all for that matter). But sure, I'm not totally discounting some software design where that makes sense. – yano May 26 '22 at 22:43
2 Answers
1
No. You return an array via a pointer (possible embedded in a struct either as a pointer or an array). The array is either dynamically allocated in the function, or passed into the function as an argument and then returned again:
char *f() {
char *s = malloc(42);
...
return s;
}
char *f2(char *s) {
...
return s;
}

Allan Wind
- 23,068
- 5
- 28
- 38
0
Java is a high-level language, C is a low-level language. in java, you could find everything already defined. in C, mostly you have to do everything. in the reality, arrays are just memory spaces that are indexed by a pointer which you don't see in Java.
returning to your question, you can create a function that inside it, you allocate the array, or you pass him as a parameter, then you do your treatment and return in simply.
i hope this clarify your inquiry.

theunknownxD
- 11
- 2