Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding integers to arrays in C++?

Consider:

int sum(const int numbers[], const int size){
    if (size == 0)
        return 0;
    else
        return numbers[0] + sum(numbers+1, size-1);
}

This is a simple recursive function from MIT 6.096 for adding an arbitrary number of integers, and it works.

The thing I cannot understand is in the last line:

How does numbers+1 work, given numbers[] is an int array and you shouldn't be able to add an integer to an int[] constant?

like image 483
Krzysztof Podsiadło Avatar asked Mar 28 '16 15:03

Krzysztof Podsiadło


People also ask

Can you add values to an array in C?

If you have a code like int arr[10] = {0, 5, 3, 64}; , and you want to append or add a value to next index, you can simply add it by typing a[5] = 5 .

How do you add elements to an array in C?

First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.


2 Answers

how does "numbers+1" work, given numbers[] is an int array and you shouldn't be able to add an integer to an int[] constant?

There's no int[] constant. numbers is decayed to a pointer and numbers+1 is simple pointer arithmetic applied to the parameter passed to the recursive call.

like image 112
πάντα ῥεῖ Avatar answered Oct 04 '22 11:10

πάντα ῥεῖ


As a side note to @πάντα ῥεῖ's answer, here are a few clarifications on the terminology:

The following is another way to depict array notation:

The phrase numbers[1] can also be expressed as *(numbers + 1) Where the * operator is said to dereference the pointer address numbers + 1. dereference can be thought of in this case as read the value pointed to by.

So, the code in your example is using pointer arithmetic. The phrase numbers + 1 is pointer notation, pointing to the second int location of the pointer numbers. size - 1 is a count of bytes from the memory location starting at numbers to the end of the array.

As to the meaning of decayed:
Generally, within the context of C array arguments, decay conveys the idea that the array argument experiences loss of type and dimension information. Your const int numbers[] is said (arguably) to decay into an int *, therefore no longer able to provide array size information. (Using the sizeof() macro for example does not provide length of array, but size of the pointer.) This also is the reason a second argument is provided, to convey size information.

However, in the context of this question, the meaning of decay is academic, as pointed out by @Ben Voigt: The token sequence const int numbers[], when it appears in a formal parameter list, declares a pointer and not an array. (It never decayed into a pointer because it was a pointer to begin with.)

like image 36
ryyker Avatar answered Oct 04 '22 11:10

ryyker