以下为了通俗易懂,使用意译。

I've here very intersting discussion about the best and common ways to return an array from a function..
我最近很热衷于讨论从函数返回数组的最佳及常用方法
Some solutions to use output parameter and copy the value of the array into the value of this output parameter array.
Other solution to pass an array and use it inside the function.

一些解决方案是使用数组作为输出参数,并将值复制到这个参数。

Others to allocate the array inside the function and return refrence to it, but the caller have to free it once done.

其他一些则是在函数内部申请空间来存放数组,并将引用(此处应该是指针地址)返回给主调函数,但调用者必须在使用完以后释放。

Others to return a struct contains this pointer...

再者就是返回一个结构,包含这个数组的指针。

 以下解决方案与诸君分享:

Please enjoy; stackoverflow.com/questions/8865982/return-array-from-function-in-c

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;
}

返回结果

684719851

 

posted on 2019-07-14 17:28  你不知道的浪漫  阅读(160)  评论(0编辑  收藏  举报