Nikos KLon
Nikos KLon

Reputation: 209

Range within an array in C

I came up with an algorithm and I wanted to ask something. Is there any way to set a range of values within an array?

Eg

int N = 10;
int array[N] = {2,6,5,9,4,3,5,9,4,9};

and using a loop to increase the start value with each pass.

for (int A = 1; A < N - 2; A++) {
    for (int B = 1; B < N - 1; B++) {
        int ProfitA = Sum(array[0...A-1]);
        int ProfitB = Sum(array[A...A+B-1]);
        int ProfitC = Sum(array[A+B...N-1]);
    }
}

So is there any way to set the range of values in each array using the above C -pseudocode?

Upvotes: 2

Views: 21855

Answers (2)

Rob
Rob

Reputation: 1974

There isn't a way using the style of syntax you used to describe what you're after.

Two obvious ways would be to provide the array and indices range (as lared mentioned) or specify the range using two pointers

int ProfitB = Sum(array + A, array + A+B-1);   /* sum array[A] ... array[A+B-1] */

Whichever approach you use, your calling code would need to ensure it provides a valid range.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

No, C does not have such functionality built in. Moreover, there is no functionality to get the upper boundary of an array once you pass it to a function (so called "decaying to pointers").

There are two standard solutions to this problem:

  • Pass a pointer to the first array element and the count of elements, or
  • Pass a pointer to the whole array, an index to the initial element, and an index to the last element

The first approach would look like this:

int sum_array(int* array, size_t len) {
    int res = 0;
    for (size_t i = 0 ; i != len ; i++) {
        res += array[i];
    }
    return res;
}
...
int ProfitA = sum_array(array, A);
int ProfitB = sum_array(array+A, B);
int ProfitC = sum_array(array+A+B, N-A-B);

the second approach would look like this:

int sum_array(int* array, int first, int last) {
    int res = 0;
    for (int i = first ; i <= last ; i++) {
        res += array[i];
    }
    return res;
}
...
int ProfitA = sum_array(array, 0, A-1);
int ProfitB = sum_array(array, A, A+B-1);
int ProfitC = sum_array(array, A+B, N-1);

Upvotes: 4

Related Questions