Amarth Gûl
Amarth Gûl

Reputation: 1082

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?

Upvotes: 4

Views: 2022

Answers (4)

Samuel Rojo
Samuel Rojo

Reputation: 11

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.

Upvotes: 0

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

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.

Upvotes: 3

Leonard
Leonard

Reputation: 13747

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.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 3

Related Questions