简体   繁体   中英

Arithmetic operations on arrays in C

我试图对C中的数组值应用算术运算。例如,如果我想为数组的每个值添加一个数字x,我应该将它分别添加到每个值,或者我可以添加x到整个数组(所以它会自动将它添加到数组的每个值)。

if I want to add a number x to each value of an array, should I add it separately to each value

Yes, you need to do it in a loop. C does not provide operators for manipulating the entire array at once.

can I add x to the whole array

An expression that looks like adding an int to an array, eg array+x , will compile, but it is a different operation altogether: when an array name is used in an arithmetic operation, it is treated like a pointer to the initial element of the array, so the result of the array+x expression is the same as &array[x] (a pointer to element of array at index x ).

Applying += to an array would not compile.

make a function that loops through your array and apply manualy your operation to each value contained in the array. There is no "buildin" function that will do that for you in C

你必须像在每种语言中一样运行整个数组。

Here is a simple function that would handle that:

void Add(int* toIncrement, int size, int increaseBy){
    for(int i = 0; i < size; ++i){
        toIncrement[i] += increasedBy;
    }
}

You can use it like this:

int thirteens[10] = {0};

Add(thirteens, 10, 13);

Note that if you wanted to write Add locally you could do that and avoid throwing a bunch of variables around.

Also if you wanted multiplication or something, just copy the function, change the function name and use *= in the place of += .

Any modification of every element in an array is done this way in C.

Here there is a simple example that can help to understand the concept of operations over arrays /* Basic Maths on arrays */

void setup()
{
  Serial.begin(9600);
  int vector[] = {2, 4, 8, 3, 6};
  int i;
  for (i = 0; i < 5; i = i + 1) 
    {
    vector[i] = vector[i]*3;
    Serial.println(vector[i]);
    }
  }
void loop()
{  
}

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