Greetings Everyone.
I\'m currently writing a multi-language programe in C, C++ and fortran on UNIX, unfortunatly I run into \"Segmentation Error\" when I try and execute
Provided you stay within the bounds of the vector, what you are doing would seem to be OK.
You can treat a std::vector exactly as if it were a C array by doing what you are doing - taking the address of the first element. The C++ Standard has been changed to specifically allow this kind of usage.
Can't find a copy of C++ the Technical Corrigendum 2003 at present, but apparently the relevant section ref is 23.2.4,
The code you posted appears to be OK - you'll need to give more detail if you want the problem debugged. Actually, if you run the program in a debugger, it should be able to tell you exactly which line of code is causing the exception (you may have to look in a call stack), or simply step through the program until it crashes.
As for the confusion about whether vector can be treated as a C array, it definitely can by getting the address of the first element (ie., &vect[0]
) - if the vector contains elements.
The C++03 standard says this about vector<>
in 23.2.4:
The elements of a vector are stored contiguously, meaning that if
v
is avector<T, Allocator>
whereT
is some type other thanbool
, then it obeys the identity&v[n] == &v[0] + n
for all0 <= n < v.size()
Note that this was not explicitly stated in the C++98 standard (but was still the intent).
See also Herb Sutter's article:
Note that vector<bool>
cannot be treated as a C array - it a special case since the elements in vector<bool>
are not stored as bool
.
You can't do that. Vector class is not the same as a C-like array.
You must convert it to a regular C array before passing it to CFE function.
Edit: Apparently my answer is wrong. Check Neil's post.
What's the content of CFE() ?
Why not define CFE() as; void CFE(float *density, float *energy, int NumElem);
So you don't have to fool around with casts and just do; density[i] = ... inside your loops?
The code that you've posted is correct. Provided that every access to an array element inside of CFE()
is within bounds, you shouldn't be getting a segmentation fault. Try running your program under valgrind and see if it reports anything unusual.