How to change multiple items at a time in C?

Say I have an array

unsigned char digit[] = {0, 1, 2, 3, 4, 5, 6, 7};

However, I want to change part of the array, to make the array look like:

{0, 1, 2, 3, 0, 0, 0, 0}

Listing each item that I want to modify and change may take some effort. Especially when there are a large number of elements that I want to change. I know that in some languages, such as Pyhton, I can do something with a single line of code:

a = np.array([0, 1, 2, 3, 4, 5, 6, 7])
a[4:] = [0, 0, 0, 0]
//a: array([0, 1, 2, 3, 0, 0, 0, 0])

So, interestingly, is there a similar way to do this in C?

+4
source share
4 answers

There are fewer options in C, but in the case of unsigned charsetting its values ​​to zero, you can usememset

memset(&digit[4], 0, 4);

Demo version

+3
source

, , , " ". , "VARARGS", .

+3

memset, , , , {1, 2, 3, 4}.

memcpy . unsigned char, , .

memcpy(&digit[4], ((unsigned char[4]){1, 2, 3, 4}), 4 * sizeof(unsigned char));

.

+3

, , , , -, , :

digit[] = {0, 1, 2, 3, 4, 5, 6, 7};   %Having this

a=the number in your vector you want to start making ceros;
n=the lenght of digit;
for(i=a;i=n;i++)
{
    digit[n]=0;
}

, . ,

b=position;
digit[b]=c; %Where c is the number you want to put in there.

, , .

0
source

Source: https://habr.com/ru/post/1691861/


All Articles