Note that there are some explanatory texts on larger screens.

plurals
  1. POMy program is good enough for my assignment but I know its not good
    text
    copied!<p>I'm just starting an assignment for uni and it's raised a question for me.</p> <p>I don't understand how to return a string from a function without having a memory leak.</p> <pre><code>char* trim(char* line) { int start = 0; int end = strlen(line) - 1; /* find the start position of the string */ while(isspace(line[start]) != 0) { start++; } //printf("start is %d\n", start); /* find the position end of the string */ while(isspace(line[end]) != 0) { end--; } //printf("end is %d\n", end); /* calculate string length and add 1 for the sentinel */ int len = end - start + 2; /* initialise char array to len and read in characters */ int i; char* trimmed = calloc(sizeof(char), len); for(i = 0; i &lt; (len - 1); i++) { trimmed[i] = line[start + i]; } trimmed[len - 1] = '\0'; return trimmed; } </code></pre> <p>as you can see I am returning a pointer to char which is an array. I found that if I tried to make the 'trimmed' array by something like:</p> <pre><code>char trimmed[len]; </code></pre> <p>then the compiler would throw up a message saying that a constant was expected on this line. I assume this meant that for some reason you can't use variables as the array length when initialising an array, although something tells me that can't be right.</p> <p>So instead I made my array by allocating some memory to a char pointer.</p> <p>I understand that this function is probably waaaaay sub-optimal for what it is trying to do, but what I really want to know is:</p> <ol> <li><p>Can you normally initialise an array using a variable to declare the length like:</p> <p>char trimmed[len];</p></li> <li><p>If I had an array that was of that type (char trimmed[]) would it have the same return type as a pointer to char (ie char*).</p></li> <li><p>If I make my array by allocating some memory and allocating it to a char pointer, how do I free this memory. It seems to me that once I have returned this array, I can't access it to free it as it is a local variable.</p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload