![]() |
|
#1
|
|||
|
|||
Vectors as arguments and C++ vs. Visual C++The following code successfully compiles and produces the expected result in Visual C++ 2008; in Linux, although it still compiles (with g++ -g ...), the result of the execution is “Segmentation fault”. Could anyone, please, explain why this is happening and what is the problem with the code?
Supposedly, VectorFunction takes in the function f of one variable x and a vector v, and computes f(v) component-wise. CPP / C++ / C Code:
|
|||
|
#2
|
|||
|
|||
Re: Vectors as arguments and C++ vs. Visual C++Quote:
Well, the following statement is invalid and keeps it from compiling. See Footnote. CPP / C++ / C Code:
Change it to CPP / C++ / C Code:
Now, it compiles, but the function has undefined behavior. The program crashes when I compile it with Visual C++ on Windows XP and also when I compile it with GNU g++ (Windows XP or Linux), but since the behavior is undefined, it is not guaranteed to crash. Since the code that you posted won't even compile, I would like to see what code you are actually using that compiles and seems to execute properly with Visual C++. Really. Anyhow... CPP / C++ / C Code:
I can think of a couple of ways to change the function so that it works with no undefined behavior. 1. Declare the vector a to have the same size as the vector v and leave everything else as is: CPP / C++ / C Code:
or 2. Leave the declaration as is, and change the statement inside the loop to push the values of v[i] into the vector: CPP / C++ / C Code:
Dave Footnote: I am having a hard time believing that Visual C++ (any version) or Linux GNU g++ (any version) or any other compiler accepts that first illegal statement that I showed. Are you sure that it compiled? Last edited by davekw7x : 28-May-2009 at 15:33.
|
|
#3
|
|||
|
|||
Re: Vectors as arguments and C++ vs. Visual C++Thanks a lot, davekw7x. You are absolutely right that
CPP / C++ / C Code:
is unvalid. The function was a template function originally, and I forgot to erase <double> while posting the message. I apologize for that. Your suggestions with respect to declaration/initialization of a vector "a" work very well. |
Recent GIDBlog
Once again, no time for hobbies by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Vectors | ultrAslan | C++ Forum | 8 | 15-Mar-2009 09:22 |
| Command Line Arguments question | bostero22 | Java Forum | 2 | 10-Mar-2009 14:06 |
| Major newbie problem | cynack | MS Visual C++ / MFC Forum | 1 | 08-Apr-2007 12:25 |
| main() arguments | crystalattice | C Programming Language | 2 | 24-Oct-2004 01:05 |
| Re: Command Line Arguments, Part 1 | WaltP | C Programming Language | 0 | 11-Jul-2004 00:34 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The