zoukankan      html  css  js  c++  java
  • Returning array from function in C

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

    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] = '';
    }

    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
  • 相关阅读:
    [SUCTF 2019]EasySQL
    [强网杯 2019]随便注
    [HCTF 2018]WarmUp
    Linux下配置JDK环境
    Centos克隆虚拟机后配置网络
    Sublime安装插件
    LeetCode-91-解码方法
    LeetCode-322-零钱兑换
    LeetCode-152-乘积最大子数组
    LeetCode-139-单词拆分
  • 原文地址:https://www.cnblogs.com/passedbylove/p/11184927.html
Copyright © 2011-2022 走看看