Search code examples
carrayshexdumpunsigned-char

Return unsigned char array to main function


Background: My original main() is:

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;
}

The original program (e.g., calculate.c) is run by command line:

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

Now I want to modify main() as a call function only, e.g., named run(). And write a new main() to call run() function.

The input (equivalent to above command line) is hardcoded in new main(). main() will pass the input value to run() function (instead of using above command line).

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

then run() returns the same output[i] to 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);
}

Question:

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

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


Solution

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

    You can represent it as an array of characters, or for example an array of arrays of characters - tokenised by whitespace. Latter is the representation that the command line arguments are already in argv.

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

    You must declare the return type of the function. It is not possible to return an array directly in C, and it is undesirable to copy arrays around. A typical solution is to let the caller (main) create the array, and let the called function modify the content of the array:

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

    main has a problem. It attempts to assign an array. Arrays are not assignable. Given that arrays cannot be returned from functions either, this makes little sense.

    This is how to call run that I've suggested:

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