Switch Switch - 2 months ago 10
C Question

Arithmetic operations on arrays in C

I am trying to apply arithmetic operations on the values of an array in C. For example, if I want to add a number x to each value of an array, should I add it separately to each value, or instead can I add x to the whole array (so would it automaticaly add it to each value of the array).

Answer

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, e.g. 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.

Comments