Possible Duplicate:
Declaring a C function to return an array
I am new to C, and need to your thoughts to help me to return the result array from the following function:
void getBase(int n, int b)
{
const size_t SIZE = 32;
char arr[32+1]={0}; int digits=SIZE, i;
char* ptr = arr;
while (n > 0)
{
int t = n%b;
n/=b;
arr[--digits] = numbers[t];
}
while ( *ptr == '\0') ptr++;
// NEED To return a ref to `ptr`
}
My solution:
void getBase(int n, int b, /*send some array as a parameter*/ char* str)
{
const size_t SIZE = 32;
char arr[32+1]={0}; int digits=SIZE, i;
char* ptr = arr;
while (n > 0)
{
int t = n%b;
n/=b;
arr[--digits] = numbers[t];
}
while ( *ptr == '\0') ptr++;
/* and use strcpy ... perhaps memcpy if non-string )*/
strcpy(str, ptr);
}
I need further ideas….
Thanks.
Your solution looks fine.
Instead, you don’t even need the local
arrarray at all. You can just write directly intostr:EDIT : Cleaned up and working version.
You just have to make sure that your
stris large enough to avoid an array-overrun.Output: