c - 从 C 函数返回数组

标签 c pointers

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/

相关文章:

pointers - Go 中独特的函数集合

C:链表并写入文件

java - 在 Java 中加密一个字符串,以便 C 程序可以解密它,而解密文本中没有任何填充?

c - 在目录中列出文件名并将它们放入字符串中 - 段错误

C 奇怪的异常,写入文件时(写入标准输出时正常工作)

c - 传递常量矩阵

c - 在将 void* 转换回 String 时遇到一些问题

c - *((int *) arg) 是做什么的?

c - 我的 fork fifo c 代码不能正常工作

c - 指针运算中的一元递增运算符