Friday, May 21, 2010

C++ help, can you help??

I need to write a function that adds the elements in two vectors, the vectors are arrays this my function defintion thus far:





//code





void vectorSum(double vecSum[], int%26amp; size){


double vec1;


double vec2;


for(int i= 0; i %26lt; size; i++){


vecSum[i]= (vec1[i] + vec2[i]);


}

C++ help, can you help??
What you miss is that both the input vectors and the output vectors must be parameters to the function. By making them parameters to the function, you tell the function what two vectors to add and where to put the sum. Also, you don't need to make size a reference.





You want something like this:





void vectorSum(double vecSum[], double const vec1[], double const vec2[], int size){


for(int i= 0; i %26lt; size; i++){


vecSum[i]= (vec1[i] + vec2[i]);


}





Now you can use your function like this:


int const v_size = 20;


int vec1[v_size];


int vec2[v_size];


int vec_sum[v_size];





// fill vec1 and vec2 with values here





vectorSum(vec_sum, vec1, vec2, v_size);


// Now vec_sum is the sum of vec2 and vec2
Reply:Some quick thoughts:





1. vec1 and vec2 haven't been defined properly.


2. vec1 and vec2 haven't been given any values.


3. Why are vec1 and vec2 inside the function? Shouldn't they be outside it?





Hope that helps.
Reply:Hello. You don't declare vec1 and vec2 as arrays. I'm just a tired old C programmer up past his bed time but it looks as if you declare them as doubles, that is as single variables, not arrays of variables, and certainly do not initialize them. If they are supposed to be global variables, why do you declare them in the block? And why aren't they arrays if you're going to treat them as arrays? If I were a good compiler, I'd assign a space for a double called vec1 and next to it a space for a double called vec2. Then if I were a good but nasty compiler, I would on the vecSum[i] line add vec1 and vec2 for 0, vec2 and whatever garbage is next to it for 1, the garbage I used for vec2[1] for the new vec1[2] and the garbage next to that...





More likely your compiler isn't nasty so it's just declaring an error and refusing to compile.





You could possibly declare them pointers and in C terms malloc a memory length of size*sizeof(double) for each. Actually you just shouldn't declare them in this function. You should pass them as parameters.


No comments:

Post a Comment