Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify multiple elements at a time in C?

Tags:

arrays

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?

like image 976
Amarth Gûl Avatar asked Jan 03 '23 23:01

Amarth Gûl


2 Answers

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.

like image 82
Sergey Kalinichenko Avatar answered Jan 05 '23 14:01

Sergey Kalinichenko


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.

like image 41
Leonard Avatar answered Jan 05 '23 13:01

Leonard