I'm confused. What is the difference between:
char *someFunction(char *src) {
char str[strlen(src) + 1];
...
return str;
}
and
char *someFunction(char *src) {
char *str = (char*)malloc((strlen(src) + 1) * sizeof(char));
...
return str;
}
The first one is with an array (char[]
) and second one is with malloc
.
What I learned in the school is that I should use malloc
if I want to make a new char-string within a function. However, it works with char[]
also within a function (like first one).
The teacher said that we must use the "heap-area", if something must be dynamically allocated.
I thought the first one with array (char str[..]
) is also dynamic because the size of char[]
is not actually known before the program begins (is this the correct understanding!?). This one works by my compiler without any problem.
Please explain the difference easily and tell me some cases where I must use malloc
and where I don't need to use it.