Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

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};
question from:https://stackoverflow.com/questions/65644488/declaring-and-initializing-char-array-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...