Is it possible to start an array at an index not zero...I.E. you have an array a[35], of 35 elements, now I want to index at say starting 100, so the numbers would be a[100], a[
C++ provides quite a bit more than C in this respect. You can overload operator[]
to do the subtraction, and if you want report an error (e.g., throw an exception) if the subscript is out of range.
As a minimal demo, consider the following:
#include <iostream>
#include <stdexcept>
template <class T, int lower, int upper>
class array {
T data[upper-lower];
public:
T &operator[](int index) {
if (index < lower || index >= upper)
throw std::range_error("Index out of range");
return data[index-lower];
}
T *begin() { return data; }
T *end() { return data + (upper-lower); }
};
int main() {
array<int, -3, 5> data;
for (int i=-3; i<5; i++)
data[i] = i;
for (auto const &i : data)
std::cout << i << "\t";
std::cout << "\n";
}
strictly speaking, this solution does not loet you define an array starting at an index different from 0, but you may declare your memory this way:
typedef union
{
unsigned char all[15000];
struct
{
unsigned char sram[10000];
unsigned char bram[5000];
};
} memory;
this does convey the intent that the memory is contiguous, and that it is split in 2 parts. note that you should beware of the alignment of bram
and sram
, a #pragma pack(1)
may be necessary.
No — as in you can't modify the lower bound in declaration like VB6.
Yes — as in you can do tricks like
int a[35];
int* actual_a = a-100;
printf("%d", actual_a[101]);
...
because x[a]
is equivalent to *(x+a)
. This is highly unrecommended.
Not in C. You have to do the arithmetic yourself. There are probably bizarre work-arounds that work most of the time, like making a new pointer that is BRAM-11000 and using that instead.
Pointers and arrays are very similar in C, so you could easilly do something like
element SRAM_MEM[10000];
element BRAM_MEM[5000];
element* SRAM = SRAM_MEM;
element* BRAM = BRAM_MEM-10000;
BRAM[10001] = 0; // sets the first element of BRAM_MEM
The simplest way to do this:
you have:
int *array = memory ; // starts with 0;
array-= 1000 ; // now array[1000] is 0
In c++ just create class with operator[]