dimanche 29 mars 2015

pointing to element before array start in C99 [duplicate]




I have an array of integers:



int* counters = (int *) calloc(N, sizeof(int));


that must be indexed using one based indexes e.g. first element has index 1, second element has index 2, etc. Since performance was very important I decided to use a trick:



int* oneIndexedCounters = counters - 1;


that allow me to use one based indexing without subtracting 1 from indexes:



// A[i] - contains one based indexes
for (int i = 0; i < K; i++) {
oneIndexedCounters[A[i]] += B[i]; // many times in code
// some other operations on oneIndexedCounters
}


insted of:



for (int i = 0; i < K; i++) {
counters[A[i]-1] += B[i];
// ...
}


counters array is returned by my function so I couldn't allocate dummy element at array beginning.


Is pointing one element before array valid (for example when array is on memory page boundary) when you are not dereferencing that pointer? Or is there other solution that is less tricky and gives good performance?




Aucun commentaire:

Enregistrer un commentaire