简体   繁体   中英

How to cast/convert an unsigned char array to a const unsigned char array in C?

I know that this is a silly question. How do you convert an unsigned char array (with values) to a const unsigned char array?

Below is the code that I have tried. It does not make sense, but a const char does not allow you to change the values (as meant by the word const) but I need a const unsigned char array to pass to a function.

#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>

int main()
{
    uint8_t a[] = {0, 10, 0, 0, 35, 45, 99, 100,88,67,34,23,56};
    unsigned char k[13];
    for(int i=0; i<sizeof(k)/sizeof(unsigned char); i++)
    {
        k[i] = a[i];
        printf("%X\t%d\n",k[i],k[i]);
    }

    // k = (const)k[]; -- cannot cast char array to const char array 

    return 0;
}

Please let me know what can be done, thanks. Below is the function declaration that k (const unsigned char *k) is to be passed.

int crypto_aead_encrypt(
    unsigned char *c, unsigned long long *clen,
    const unsigned char *m, unsigned long long mlen,
    const unsigned char *ad, unsigned long long adlen,
    const unsigned char *nsec,
    const unsigned char *npub,
    const unsigned char *k
) 

const here is a qualifier meaning "this function will not alter this variable". It's a guarantee about the function's behavior, not about what you're passing in. It's ok to pass a non-const variable to a function taking a const.

For example, the following is fine. It's ok to pass a char * to const char * . main is allowed to alter the string, but foo is not.

void foo(const char *a) {
    puts(a);
}

int main()
{
    char *str = strdup("testing");
    foo(str);
}

However, the following is an error. It doesn't matter that str was not declared with const , foo promised not to modify its argument.

void foo(const char *a) {
    // error: assignment of read-only location '*a'
    a[0] = 'r';
    puts(a);
}

int main()
{
    char *str = strdup("testing");
    foo(str);
}

You should not go the other way. Passing a const to a non-const function is undefined. It might work, it might not.

// note: expected 'char *' but argument is of type 'const char *
void foo(char *a) {
    a[0] = 'r';
    puts(a);
}

int main()
{
    const char str[] = "testing";

    // warning: passing argument 1 of 'foo' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
    foo(str);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM