Return 无符号字符数组到主函数

Return unsigned char array to main function

背景:我原来的main()是:

int main(int argc, char *argv[])
{
    unsigned char output[16] = {0x00};  // copied from code

    // .... (some steps to calculate output[i])

    for (i = 0; i < 16; i++)
    {
        printf("%02X ", output[i]); // output[i] is an array of 16-byte hex values
    }

    return 0;
}

原程序(如calculate.c)是运行命令行:

./calculate $(echo "this_is_input"|xxd -p)

现在我想将main()修改为仅调用函数,例如命名为运行()。并编写一个新的 main() 来调用 运行() 函数。

输入(相当于上面的命令行)在新的 main() 中被硬编码。 main() 会将输入值传递给 运行() 函数(而不是使用上面的命令行)。

run(int argc, char *argv[])
{
    ....
    return output[i];
}

然后 运行() returns 相同的输出[i] 到 main()

int main()
{
    input_char = **equivalent to $(echo "this_is_input"|xxd -p)** // how to define?

    unsigned char returned_output[16] = {0x00};

    returned_output = run(X, input_char);

    print(returned_output);
}

问题:

  1. 如何在 main() 中显示 $(echo "this_is_input"|xxd -p)** 的十六进制转储值?

  2. 如何修改 运行() 和 main() 以便 return unsigned char 数组到 main()?

  1. How to present the hex dump value of $(echo "this_is_input"|xxd -p)** in the main()?

您可以将其表示为字符数组,或者例如字符数组的数组 - 由空格标记。后者表示命令行参数已经在argv.

  1. How to modify run() and main() in order to return unsigned char array to main()?

您必须声明函数的 return 类型。在C中直接return一个数组是不可能的,到处复制数组也是不可取的。一个典型的解决方案是让调用者(main)创建数组,让被调用的函数修改数组的内容:

void run(int argc, char *argv[], unsigned char output[16])

main 有问题。它尝试分配一个数组。数组不可赋值。鉴于数组也不能从函数 returned,这没有什么意义。

这是我建议的 运行 的调用方式:

unsigned char output[16] = {0x00};
run(argc, argv, output);