0

I am having trouble converting type vector< vector > to an array.So far, I've tried to do the following (with help from /u/ Robert Crovella)

pos_x_h=(double *)malloc(N*sizeof(double)); pos_y_h=(double *)malloc(N*sizeof(double)); for (int i = 0; i<N; i++){ vector<double> temp = r[i]; pos_x_h[i] = temp[i][0]; pos_y_h[i] = temp[i][1]; } 

Here, r is the position vector with N elements each having x and y components. I also tried doing

double arr[N]; std::copy(r.begin(), r.end(), arr); 

Both attempts didn't work, and I'm not sure why. You can see the code here.

1
  • 2
    You don't need to index temp with two indices. Just use temp[0] and temp[1]. And if you #include <stdlib.h> you don't need to (and shouldn't) cast the return value of malloc. That's "old" C (I know… I learnt that from the 1982 K&R book before I got wise.) Commented Apr 13, 2014 at 4:46

1 Answer 1

2

The following ought to work. Note that I prefer sizeof *pos_x_h over sizeof(double) since the former makes sure the size is correct even if you change the type of the variable (which might be in another piece of code). updated* for C++ you need to cast the result of malloc. I was thinking with my C hat on...

second update

A bit more thought tells me you really don't want to have temp as a vector - that is just making things more confusing. Instead, point to the address of the first element of r[i]: this compiles without errors

 pos_x_h=(double *)malloc(N*sizeof(double)); pos_y_h=(double *)malloc(N*sizeof(double)); for (int i = 0; i<N; i++){ double* temp; temp = &r[i][0]; pos_x_h[i] = temp[0]; pos_y_h[i] = temp[1]; } 

Of course you could simply do

 pos_x_h=(double *)malloc(N*sizeof(double)); pos_y_h=(double *)malloc(N*sizeof(double)); for (int i = 0; i<N; i++){ pos_x_h[i] = r[i][0]; pos_y_h[i] = r[i][1]; } 

and avoid the whole mess.

Sign up to request clarification or add additional context in comments.

8 Comments

Can you please add a comment that it is better to use new in a c++ code, as tagged by the OP?
Gaahhh...this still doesn't work. This also gives me the same errors 1)incompatible types in assignment, 2)cannot convert ‘double’ to ‘double*’ in assignment. What is going on here? cries
@0x90 I am not exactly sure where that would help in this case, as each iteration in the loop uses a new instance of temp (it is pointing to a new value). Could you clarify?
@MisterSpock Can you show the actual definition of r please - maybe I misunderstand what type it is. But I am guessing that you need temp to be of the type double*. I made the edit in my answer - see if that helps.
here is the code. each item in r vector has (x,y) values which are both double.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.