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 arr array at all. You can just write directly into str:
EDIT : Cleaned up and working version.
const char numbers[] = "0123456789abcdef";
void getBase(int n, int b, char* str)
{
const size_t SIZE = 32;
int digits=SIZE;
while (n > 0)
{
int t = n%b;
n/=b;
str[--digits] = numbers[t];
}
int length = SIZE - digits;
memmove(str,str + digits,length);
str[length] = '\0';
}
You just have to make sure that your str is large enough to avoid an array-overrun.
int main(){
char str[33];
getBase(684719851,10,str);
printf(str);
return 0;
}
Output:
684719851
As other mention, the common solution is to allocate an array, an return a pointer to it. Be sure that you free it in the caller function.
If you know (at compilation time) the size of the array, you can make a struct that contain an array, and return the struct. note that it will push the array to the stack, and may slow the program. If it's a really big array you even may get a stack overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With