Possible Duplicate:
Declaring a C function to return an array
我是 C 语言新手,需要您的想法来帮助我从以下函数返回结果数组:
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`
}
我的解决方案:
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);
}
我需要进一步的想法......
谢谢。
最佳答案
您的解决方案看起来不错。
相反,您甚至根本不需要本地 arr
数组。您可以直接写入str
:
编辑:清理后的工作版本。
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';
}
您只需确保您的 str
足够大以避免数组溢出。
int main(){
char str[33];
getBase(684719851,10,str);
printf(str);
return 0;
}
输出:
684719851
关于c - 从 C 函数返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8865982/