i’m quite familiar with Java, not so in C.
In Java, if i have a method that does something and returns a String, it would look like:
private String doSomething(...) {
String s;
// do something;
return s;
}
The syntactic equivalent in C would not work and is plain wrong:
char* doSomething(...) {
char s[100];
// do something;
return s;
}
of course i can do:
char* doSomething(...) {
char *s;
s = malloc(100 * sizeof(char));
// do something;
return s;
}
which would work (i think!) but i seldom see codes doing this way (is it because it’s unnecessarily filling the heap?)
most commonly, i see:
bool doSomething(char *s) {
// do something that copies chars to s
return true;
}
And the calling statements would be:
char s[100];
doSomething(s);
What if I do not know the size of the char array until inside the function itself? i.e. I would not be able to declare the char array outside the function and then pass it in.
What would be the correct way to deal with such a scenario?
An example of static allocation case (you are obliged to think about the maximum buffer size at compile time)
or dynamic allocation case (using malloc as you said and using pointers to save the buffer location and size)