If the signature of the coiso() function is given and you are asked to implement its body, then assuming the signature is the one you provide in the 1st post ...
Code:
const char *coiso(int chave);
then I guess your best bet would be to allocate the string inside the function, populate it using the exact size it needs (a wild guess, because of the const ), and then return it.
So, assuming chave is expressed as a base-10 integer, and that negative values are acceptable, but 0 is not, then it could be something like this...
Code:
const char *coiso( int chave )
{
const char *const ending = ".txt"; /* needless const nitpicking :P */
char *ret = NULL; /* cstring to be returned */
size_t sz = strlen(ending) + 1; /* init to ending's size */
int ndigits = 1; /* count of chave's digits */
int temp = chave;
/* sanity check */
if ( 0 == chave ) {
return NULL;
}
/* count digits in chave (assuming chave is expressed in base-10) */
while ( 0 != (temp /= 10) ) {
ndigits++;
}
/* allocate mem for ret */
sz += (chave > 0) ? ndigits : ndigits+1; /* +1 for minus sign, if any */
ret = malloc( sz /* * sizeof(char) */ );
/* populate ret */
if ( ret ) {
sprintf( ret, "%d%s", chave, ending );
}
return (const char *)ret;
}
What puzzles me though a bit with that signature, is the const qualifier for the returned string.
Since the returned string should be freed by the caller when done using it, that const qualifier forces us to either explicitly cast the string in the caller context when creating it via coiso()...
Code:
int main( void )
{
char *info = (char *)coiso(1223);
...
free( info );
return 0;
}
or define info as (const char *) and then explicitly cast it to (char *) when passing to free()...
Code:
int main( void )
{
const char *info = coiso(1223);
...
free( (char *) info );
return 0;
}
otherwise the compiler will complain (usually with just a warning) when trying to free the string.
It would be better if the const qualifier were missing, but if you must use it, you must use it
On the other hand, if you are free to choose your own signature for the function, you can do whatever you like... even making it void and pass to it a pre-allocated buffer to be filled-in.
@jimbluberg:
Sure, but both those functions expect pre-allocated buffers to get passed to them.