简体   繁体   中英

Declaring and initializing char array in C++

I am trying to declare and initialize a unsigned char arr within if else block, but im seeing " cannot convert '' to 'unsigned char' in assignment" error. Can anyone please help me understand whats wrong with this? I am new to c++.

Edited:

unsigned char arr[4]; 
if (..){
    arr[4] = {0x0F, 0x0F, 0x0F, 0x0F};
} else {
    arr[4] = {0xFF, 0xFF, 0xFF, 0xFF};
}

Going the below way doesn't have any issue. But I need assignment happening inside if-else so am trying to understand whats the problem with above snippet?

unsigned char arr[4] = {0xFF, 0xFF, 0xFF, 0xFF};

I'm afraid that initializer syntax you are trying to use is only possible for variable declarations.

Possible solution are to declare a new array and copy it using memcpy

#include <iostream>
#include <cstring>

int main()
{
    unsigned char arr[4] =  {0x0F, 0x0F, 0x0F, 0x0F};
    if (elsecondition){
        unsigned char arr1[4] = {0xFF, 0xFF, 0xFF, 0xFF};
        memcpy(arr, arr1, sizeof(arr));
    }
return 0;
}

or to do the assignment one element at a time

#include <iostream>

int main()
{
    unsigned char arr[4] =  {0x0F, 0x0F, 0x0F, 0x0F};
    if (elsecondition){
        // we can use a loop, since all values are identical
        for (int i = 0; i < sizeof(arr); ++i)
            arr[i] = 0xFF;
    }
return 0;
}

First of: arr[4] = {0x0F, 0x0F, 0x0F, 0x0F}; will try to assign something to the 5th element of the array (but the types are not compatible and it would be an out-of-bounds-access).

This syntax is only availble in array initialization, however std::array overloads operator= and supports what you want:

std::array<unsigned char, 4> arr; 
if (...){
    arr = {0x0F, 0x0F, 0x0F, 0x0F};
} else {
    arr = {0xFF, 0xFF, 0xFF, 0xFF};
}

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