Last active
May 6, 2019 07:59
-
-
Save drikosev/47501efc62041adc79c7a4ca78d24d02 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct dim { | |
int lower; | |
int upper; | |
}; | |
struct array { | |
struct dim one, two; | |
int* buffer; | |
int** index; | |
int offset; | |
}; | |
int pos(struct array a, int i, int j) { | |
int rc= a.offset | |
+ ( (1 + a.two.upper - a.two.lower) * (i) ) | |
+ j ; | |
return rc; | |
}; | |
int cell(struct array a, int i, int j) { | |
return * (a.buffer+pos(a,i,j)); | |
}; | |
void allocate( struct array *a ) { | |
int size1=(1 + a->one.upper - a->one.lower) ; | |
int size2=(1 + a->two.upper - a->two.lower) ; | |
int size = size1 * size2 ; | |
a->buffer=malloc(size*sizeof(int)); | |
a->offset = ( 0 - a->one.lower ) * ( size2 ) | |
+ ( 0 - a->two.lower ) ; | |
//initialize & print | |
printf(" Initialized\n"); | |
int pos=1; | |
int *p=(int *) a->buffer; | |
for ( int i=0;i<size1;i++) { | |
for (int j=0;j<size2;j++){ | |
*p = pos ; | |
printf(" %d, ", *p ); | |
p++; | |
pos++; | |
} | |
} | |
printf("\n"); | |
} | |
int** create_index(struct array *a ) { | |
int size1=(1 + a->one.upper - a->one.lower) ; | |
int size2=(1 + a->two.upper - a->two.lower) ; | |
a->index=malloc( size1 * sizeof( size_t ) ); | |
for (int i=0; i<size1; i++) { | |
a->index[i]= a->buffer + i * size2 - a->two.lower; | |
}//for | |
a->index = a->index - a->one.lower ; | |
return a->index; | |
}// | |
void bounds(){ | |
int i,j; | |
struct array a={ {-3,3}, {-2,2}, NULL , NULL, 0 }; | |
allocate(&a); | |
printf(" Allocated\n"); | |
for ( i = -3 ; i <= +3 ; i++ ) { | |
for ( j = -2 ; j <= +2 ; j++ ) { | |
printf("a[%2d][%2d]=%d\n ", i,j, cell(a,i,j) ); | |
} | |
} | |
int** array = create_index(&a); | |
printf(" Indexed\n"); | |
for ( i = -3 ; i <= +3 ; i++ ) { | |
for ( j = -2 ; j <= +2 ; j++ ) { | |
printf("a[%2d][%2d]=%d\n ", i,j, array[i][j] ); | |
} | |
} | |
}//bounds | |
int main() { | |
bounds(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment