Should I convert FORTRAN code to C?

der Mouse mouse at mcgill-vision.UUCP
Sun Jun 26 20:51:59 AEST 1988


In article <738 at naucse.UUCP>, rrr at naucse.UUCP (Bob Rose ) writes:
> In article <20340 at beta.lanl.gov>, jlg at beta.lanl.gov (Jim Giles) writes:
>> The Problem is that 2-d arrays are not optimizable because they are
>> immediately turned into pointer-to-pointer-to-data type of
>> constructs.

> Ok, what gives. Some else post the following code (not exact but
> close enough)

> 	real a(5,2)
> 	call foo(a)
> 	end

> 	subroutine foo(a)
> 	real a(10)

> Now doesn't the following c code work to do the same

> 	double a[2][5]        /* <-- note [2][5] not [5][2] */
> 	....foo(a)....

> 	void foo(double a[10]) { ... }

No, I'm afraid not.  foo() is expecting an array of ten doubles.
Instead, you're passing it an array of two arrays of five doubles.
(Actually, a pointer to an array of five doubles.)

What's the difference?  To put it briefly, I find no guarantee that
sizeof(double[5]) == 5*sizeof(double).  (If that didn't make sense to
you, read on.)  Of course, most compilers won't produce surprises like
this, but that's no guarantee that some machine won't come along on
which there are good performance reasons for doing it.

A is just an array of two elements.  Like other arrays of two elements,
the memory allocated for it can be thought of as being in two pieces:
one for each element.  By the definition of pointer arithmetic and its
relation to arrays, the distance from the start of the first piece to
the start of the second piece is the size of the thing a is an array
of.  When the elements of an array are, say, structures, nobody finds
this surprising.  For example, suppose we have

struct { int i; char c; } b[2];

Now suppose sizeof(int)==2.  Then that structure really *needs* only
three bytes of storage.  However, the compiler is free to waste a byte
and decree that the structure type takes up four bytes, one of which
has no name.  As far as I can tell, the same is true of arrays: if I
declare

char c[3];

the compiler is free to do the same padding trick and make c take up
four bytes, one of which has no name.  Of course the same is true of
arrays of five doubles.  So when we allocate an array of two such
arrays, the compiler may put padding in between.

					der Mouse

			uucp: mouse at mcgill-vision.uucp
			arpa: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list