How is it that I can assign a char* variable a string, and do not have to allocate memory previously?
For example if I have a function return a char* (a file path for example) and I would call the function this way.
char* path;
path = get_path();
How could I expect the char* to behave if I do not know what the length of the path will be?, is it strictly necessary to allocate the path’s size prior it’s assignment to “Path” ?
In your code:
get_pathreturns a pointer to (or, equivalently, the address of) a string. (A pointer to a string is a pointer to its first character). The assignment simply copies that pointer value, storing it inpath.The
get_pathfunction itself must have allocated space to hold the string somehow.There are several ways it could have done that. Some make it the caller’s responsibility to deallocate the space when it’s no longer needed.
Recommend reading: the comp.lang.c FAQ, especially sections 4 (Pointers), 6 (Arrays and Pointers), 7 (Memory Allocation), and 8 (Characters and Strings).