简体   繁体   中英

How to modify multiple elements at a time in C?

Say I got an array

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

Yet I want to modify part of the array, make the array become something like:

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

Enumerate every element I want to modify and alter them might take some effort. Especially when there's a large amount of elements I want to change. I know in some languages like Python I may do something using 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 I wonder, is there a similar way to do that in C?

There are fewer possibilities in C, but in case of an unsigned char and setting its values to zero you could use memset :

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

Demo.

One options is that you could write a subroutine that would implement the interface that other languages provide "under the cover". You'll probably want to educate yourself on 'VARARGS' to make it take a variable number of arguments.

Others have already mentioned setting the array elements to a single value using memset , as a part of your follow up question you asked if some elements can be set to certain values like {1, 2, 3, 4} .

You can use memcpy here to achieve that. Since your type here is unsigned char I will keep that, but in general this method can be used for any type.

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

You can see the demo here .

I think that maybe not the shortest but something you can easy do is just:

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

Is just a way I think you could use. If you want to change an specific one just

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

I hope it works for you, good luck.

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