Arrays with arbitrary offset in C
Posted: Mon Dec 13, 2004 12:19 pm
It's been almost a year since I switched from Pascal to C. Both languages have their strong and weak areas, and I refrain from giving an opinion on which is the better of the two. Code written in C is on average faster then the same code in Pascal for the problems here on UVA, but I don't think C is faster than Pascal in general.
There are, however, some language features from Pascal that I keep missing in C. The WITH ... DO ... construction, local functions and arrays with arbitrary offset are the features I miss most. On this last issue I need your help.
In Pascal you can declare a one dimensional array with any (integer) range, f.i.[pascal]myarray: array[-30..45] of integer;[/pascal] after which you can use all array elements from myarray[-30] upto myarray[45]. It's not so difficult to do the same in C with the help of a pointer:[c]int dummy[76];
int *myarray=&dummy[30];[/c]and now you can also access all elements of dummy[] using myarray[-30] upto myarray[45].
But for two (and higher) dimensions the situation is not clear to me. How should I declare the C equivalent of[pascal]myarray2: array[-20..20,-20..20] of integer;[/pascal]I want to access all elements of dummy2[][] with expressions like myarray2[-7][3], myarray2[9][0], etc. I have the feeling that it should be possible, but I don't know how. The simplest looking way[c]int dummy2[41][41];
int *myarray2[][41]=&dummy2[20][20];[/c]doesn't work.
There are, however, some language features from Pascal that I keep missing in C. The WITH ... DO ... construction, local functions and arrays with arbitrary offset are the features I miss most. On this last issue I need your help.
In Pascal you can declare a one dimensional array with any (integer) range, f.i.[pascal]myarray: array[-30..45] of integer;[/pascal] after which you can use all array elements from myarray[-30] upto myarray[45]. It's not so difficult to do the same in C with the help of a pointer:[c]int dummy[76];
int *myarray=&dummy[30];[/c]and now you can also access all elements of dummy[] using myarray[-30] upto myarray[45].
But for two (and higher) dimensions the situation is not clear to me. How should I declare the C equivalent of[pascal]myarray2: array[-20..20,-20..20] of integer;[/pascal]I want to access all elements of dummy2[][] with expressions like myarray2[-7][3], myarray2[9][0], etc. I have the feeling that it should be possible, but I don't know how. The simplest looking way[c]int dummy2[41][41];
int *myarray2[][41]=&dummy2[20][20];[/c]doesn't work.