First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.
Second, use strlen
to measure the exact used length of string stored before, and malloc
to allocate memory in heap, whose length is defined by strlen
. The code is shown below.
int strLength = strlen(strInStack);
if (strLength == 0) {
printf("\"strInStack\" is empty.\n");
}
else {
char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
strcpy(strInHeap, strInStack);
}
return strInHeap;
Finally, copy the value of strInStack
to strInHeap
using strcpy
, and return the pointer to strInHeap
. The strInStack
will be freed automatically because it only exits in this sub-function.