简体   繁体   中英

c++ function returns array with offset

I am working with some C code (not my own) that interfaces with Fortran and insists that all arrays be 1-based. I have a method that returns (a pointer to) an array that I have to line up correctly. The following works:

double* a;
...
a = returnedArray(arraySize);

Now what I need is to get the return to align at a[1], a[2], ... instead. (Of course I could shift things around manually, but there has to be a better way.) I tried to get the compiler to accept

a[1] =  returnedArray(arraySize);
*(a+1) = ...

and several other permutations, without success. A web search has not given me anything useful, either.

尝试:

 `a=returnedArray(arraySize)-1;`

You cannot change that fact that returnedArray() returns a pointer to the first element of your array. And in C arrays, the first element is inevitably index 0.

However, if you offset the pointer by one element before using it, maybe you'll achieve your goal?

double * a;
...
a = returnedArray(arraySize) - 1;
...
double firstValue = a[1];

However, I strongly suggest you stick with index 0 being the first element, and fix the interfacing with Fortran in some other way. Surely, at some point you'll introduce a hard-to-find bug if you keep mixing 0-based and 1-based arrays in your code.

You want to do something like that ? the array a start at tab[1]

   double tab[10];
   for(int i = 0 ; i < 10 ; i++){
    tab[i] = i;
   }

   double *a = &tab[1];
   for(int i =0 ; i < 9 ; i++){
    cout << a[i] << endl;
   }

If the memory between Fortran and C is being shared (eg. not copied), you cannot change the indexing of the built-in C type yourself. However, you could make a wrapper for your arrays returned from Fortran, which would make accessing them more convenient, and make it quite clear the difference between 1-indexing and 0-indexing. For example:

class FortranArrayWrapper
{
public:
   FortranArrayWrapper(double* a) : A(a) { }
   operator double* () const 
   {
      return &A[1];
   }
   double* A;
};

FortranArrayWrapper a(returnedArray(arraySize));
a[0] = ...; // Index 1 in the array returnedArray, ie. first element in the Fortran array.
a.A[0] = ...; // Actually index '0', unused by Fortran.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM