You are confusing the "present contents of the output parameter" with "available space". The former is irrelevant, and the only information you have about the latter is "there is at least this much space available".
Now it will depend on how the space for output
was assigned in the first place. If you did something like
char output[100];
strcpy(output, "hello");
You would end up with space for 100 characters, but only 6 (5+1) actually used. You could therefore take the string "ThiS IS a STRING" and process it with your function, without problem.
But this is not safe, because you don't know how much space there is. The following approach would be better:
char *output;
output = malloc(100);
Now change your function prototype to
void makeUpper( const unsigned char* input, unsigned char** output )
and in your function, you do
inputLength = strlen(input);
*output = realloc(*output, inputLength + 1);
This will make sure that enough space is allocated for the output. Or you could return the value in the input vector - you already know there is enough space there...
EDIT In the example you give, there is enough space in the output
; the question simply becomes one of "safely copying" the (uppercased) input to the output. In which case your function can look like this:
void makeUpper( const unsigned char* input, unsigned char* output )
{
int inputLength = strlen(input);
int outputLength = strlen(output);
int ii;
for (ii = 0; ii < inputLength; ii++)
{
output[ii] = toupper(input[ii]);
}
if(outputLength < inputLength) output[ii] = '\0';
}
The final line is there to make sure that if you increased the length of output
(again, assuming this was memory you could validly access), then you still need to make sure there's a terminating nul
character at the end of the string. In your example, you want the "rest of the output string" to still be there when the input
is shorter than the output
, so you need the if
condition.
In general - if you do not know for sure that output
is big enough, there is no way to make it bigger without having access to the address of the pointer - sometimes called the "handle".