作为参数传递给函数的数组的长度

时间:2020-05-01 16:26:28

标签: arrays bash arguments

我需要将数组作为参数传递给函数(可以),然后获取其长度(我不希望这样做)。

工作示例:

HWND hwnd;

int main() {
    std::thread t([] {
        // let GUI run in its own thread ...
        WinMain(GetModuleHandle(NULL), NULL, "", SW_SHOWDEFAULT);
        exit(0);
    });
    // meanwhile in this thread we handle console I/O ...
    std::string s;
    std::cout << "Press Enter to exit" << std::endl;
    while (std::getline(std::cin, s)) {
        if (s == "")
            break;
        std::cout << "Hello " << s << std::endl;
    }
    PostMessageA(hwnd, WM_CLOSE, 0, 0);
    t.join();
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
     // Your normal WinMain.
     // CreateWindow, GetMessage loop etc. . .

输出为:

function foo {
 declare -a idn=("${!1}")
 echo "idn=${idn[@]}"
 n=${#idn[@]}
 echo "n=$n"
}

identifier=(a b c d e)
echo "len is ${#identifier[*]}"
echo foo
foo identifier[*]

外部函数的长度还可以,但是不在函数内部。

我正在使用GNU bash版本4.3.42(1)-发行版(x86_64-suse-linux-gnu)

3 个答案:

答案 0 :(得分:2)

使用 -n ameref变量,如下所示:

#!/usr/bin/env bash

foo ()
{
  # If argument 1 is not an array, return an error
  [ "${!1@a}" = 'a' ] || return 2

  # Make idn a nameref variable referrencing the array name from argument 1
  declare -n idn="$1"

  echo 'idn:' "${idn[@]}"
  n=${#idn[@]}
  echo 'n:' "$n"
}

identifier=(a b c d e)
echo "len is ${#identifier[*]}"
echo foo
foo identifier

或将数组元素作为值传递:

#!/usr/bin/env bash

foo ()
{
   declare -a idn=("${@}")

   echo 'idn:' "${idn[@]}"
   n=${#idn[@]}
   echo 'n:' "$n"
}

identifier=(a b c d e)
echo "len is ${#identifier[*]}"
echo foo
foo "${identifier[@]}"

答案 1 :(得分:2)

您的原始脚本应该可以通过将最后一行更改为:

foo "identifier[@]"

答案 2 :(得分:0)

如果要将数组abcde的各个参数传递给函数,请使用{{ 1}}。然后,您可以在函数中使用foo "${identifier[@]}"来获取参数数量。

或者,如果要将变量名传递给函数,则可以使用本地$#变量nameref, 是对idn数组的引用。

identifier

输出:

foo() {
  echo "n=$#"
}

foo2() {
  local -n idn=$1
  echo "n=${#idn[@]}"
}

identifier=(a b c d e)
echo "len is ${#identifier[*]}"
foo "${identifier[@]}"
foo2 identifier