abed@saturn.wustl.edu (Abed M. Hammoud) (04/27/91)
Hello, I hope this question will not upset anyone, .... I use two dimensional matrices very frequently. Negative indexing is inherent in some of the applications that I write. So I like being able to say for example x[-10][-20]...etc... For sometime I used the C code in Numerical recipes that suggest using the following: for example to declare an int matrix x with indices i=-10, 10 and j=-10, 10; you would call the function below: x = imatrix(-10, 10, -10, 10); ^ ^ ^ ^ nrl nrh ncl nch Then to access the ith, jth element you type x[i][j]. Listed below is the function imatrix, /*----------------------------------------------------------------------*/ /*----------------------------From Numerical Recipes-------------------*/ int **imatrix(int nrl, int nrh, int ncl, int nch) { int i,**m; m=(int **)malloc((unsigned int) (nrh-nrl+1)*sizeof(int*)); if (!m) nrerror("allocation failure 1 in imatrix()"); m -= nrl; for(i=nrl;i<=nrh;i++) { m[i]=(int *)malloc((unsigned int) (nch-ncl+1)*sizeof(int)); if (!m[i]) nrerror("allocation failure 2 in imatrix()"); m[i] -= ncl; } return m; } /*----------------------------------------------------------------------*/ The above method is ok, but the array elements are not contiguous in memory. So, I looked up the CFAQ to see what info does it have about this and I got the following.... /*----------------------------------------------------------------------*/ /* ------from CFAQ-----------------*/ You can keep the arrays contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic: >>int **array = (int **)malloc(nrows * sizeof(int *)); >>array[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); >>for(i = 1; i < nrows; i++) >> array[i] = array[0] + i * ncolumns; /*----------------------------------------------------------------------*/ The above code worked fine, I can access the ith, jth element by typing x[i][j] or by just incrementing a pointer. But the above code does not allow -ve indexing....I tried to modifiy it but I was not successfull.... So my question is, can any body help me in making the above code work so that I can have -ve indexing. I would Appreciate any comments, No flames please.... -------------------------------------------------------------- | Abed M. Hammoud abed@saturn.wustl.edu| | Washington University. office:(314)726-7547 | | Electronic Systems & Signals Research Laboratory. | | Dept. of Electrical/Biomedical Engineering. | | St.Louis Mo U.S.A | --------------------------------------------------------------