1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
/* pas de moi
http://clubnix.fr/node/382 */
void* array_alloc (int n, int tab[], size_t elemSize)
{
int i,j;
int pro;
int sum;
size_t dataSize;
size_t blocSize = 0;
void* ptrAlloc;
void *ptrBase, *ptrP;
if (tab == NULL || n == 0 || elemSize == 0) {
return NULL;
}
if (n == 1) {
return malloc (tab[0] * elemSize);
}
sum = 0;
pro = 1;
for (i = 0; i < n - 1; i++){
pro *= tab[i];
sum += pro;
}
blocSize = sum * PTR_SIZE + pro * elemSize * tab[i];
if ((ptrAlloc = malloc (blocSize)) == NULL){
return NULL;
}
ptrBase = ptrP = ptrAlloc;
for (i = 0, pro = 1; i < n - 1; i++) {
pro *= tab[i];
ptrBase += pro * PTR_SIZE;
dataSize = (i == n - 2) ? elemSize : PTR_SIZE;
for (j = 0; ptrP < ptrBase; ptrP += PTR_SIZE, j++) {
*((void**)ptrP) = ptrBase + tab[i+1] * j * dataSize;
}
}
return ptrAlloc;
} |
Partager