I have to replace some Fortran subroutines with C++ functions. Since the literature is poor, I am stuck with a problem like the following one.
My code always throws an error:
Program received signal SIGSEGV: Segmentation fault - invalid memory reference.
This is my Fortran code:
PROGRAM vector_adder
IMPLICIT NONE
INTEGER,DIMENSION(3) :: a,b,c
INTEGER :: i
!C fill vectors with values
DO i = 1,3
a(i) = i
b(i) = i
END DO
CALL ADD_VECTORS(a,b,c)
WRITE(*,'(I5,I5,I5)') (c(i),i =1,3)
STOP
END PROGRAM
A working C code:
void add_vectors_(int (*a)[3], int (*b)[3], int (*c)[3])
{
for(int i = 0; i<3 ; i++)
{
(*c)[i] =(*a)[i] + (*b)[i];
}
}
And I would like a similar one in C++:
extern "C" void add_vectors_(std::vector<int> *a, std::vector<int> *b, std::vector<int> *c)
{
for(int i = 0; i<a->size() ; i++)
{
(*c)[i] =(*a)[i] + (*b)[i];
}
}
You are mixing your fortran
, C
lingo of vector
which refers to a collection of int
s in contiguous memory location i.e an array
with C++
's std::vector
. std::vector
is a separate container class altogether and needs construction - refer to the documentation