How can I return an array?

2020-06-27 06:54发布

Is there any way to return an array from a function? More specifically, I've created this function:

char bin[8];

for(int i = 7; i >= 0; i--)
{
    int ascii='a';
    if(2^i-ascii >= 0)
    {
        bin[i]='1';
        ascii=2^i-ascii;
    }
    else
    {
        bin[i]='0';
    }
}

and I need a way to return bin[].

9条回答
家丑人穷心不美
2楼-- · 2020-06-27 07:49

I think your best bet is to use a vector. It can function in many ways like an array and has several upsides (length stored with type, automatic memory management).

void Calculate( std::vector<char>& bin) {
  for(int i = 7; i >= 0; i--)
  {
    int ascii='a';
    if(2^i-ascii >= 0)
    {
        bin.push_back('1');
        ascii=2^i-ascii;
    }
    else
    {
        bin.push_back('0');
    }
  }
}
查看更多
等我变得足够好
3楼-- · 2020-06-27 07:50

you need to pass array bin as an argument in your function. array always pass by address, therefore you dont need to return any value. it will automatically show you all changes in your main program

void FunctionAbc(char bin[], int size);


void FuncationAbc(bin, size)
{
for(int i = 7; i >= 0; i--)
{
    int ascii='a';
    if(2^i-ascii >= 0)
    {
        bin[i]='1';
        ascii=2^i-ascii;
    }
    else
    {
        bin[i]='0';
    }
}

}
查看更多
可以哭但决不认输i
4楼-- · 2020-06-27 07:52

I think that everyone else answered this one... use a container instead of an array. Here's the std::string version:

std::string foo() {
    int ascii = 'a';
    std::string result("00000000");
    for (int i=7; i>=0; --i) {
        if (2^i-ascii >= 0) {
            result[i] = '1';
            ascii = 2^i-ascii;
        }
    }
    return result;
}

I'm not really sure if 2^i-ascii is want you want or not. This will be parsed as (2 ^ (i - ascii)) which is a little strange.

查看更多
登录 后发表回答