I'm having some trouble making a program that asks for any vectors (of any size) and then outputs them. I intend to modify this at some point to calculate cross products, dot products etc.
Unfortunately, I can't get the program to do either! I decided to focus on the output part of the problem first:
First of all, you are only passing the address of your first element of your array, but not it's length. If you would format your code a little bit more decent, it would probably point to the line with the for()-statement. The sizeof() returns an size_t.
When an array is passed to a function as a parameter it is impliciitly converted to the pointer to its first element. It is why you declared your function as
void disp(int *p);
Its parameter is pointer to int. The sizeof of a pointer is equal (usually) to 4 bytes. It is not the size of the array that you passed to the function. It is size of the pointer.
So inside your function the size of the array the first element of which the pointer references to is unknown.
So you should add second parameter which will specify size of the array.
In this case the definition of the will look like
1 2 3 4 5
void disp( int a[], size_t n )
{
for ( size_t i = 0; i < b; i++ ) std::cout << a[i] << ' ';
std::cout << std::endl;
}
/*
Calculates the dot product of two vectors.
*/
#include<iostream>
usingnamespace std;
void disp(double *p, int t);
double dot(double *p, double *q);
int main(){
int k, i;
cout << "Enter vector space dimension: ";
cin >> k;
double p[k], q[k];
cout << "Enter the first vector (row form): ";
for(i=0;i<k;i++){ cin >> p[i];}
cout << "Enter the second vector (row form): ";
for(i=0;i<k;i++){ cin >> q[i];}
disp(p,k);
disp(q,k);
cout << dot(p,q) << '\n';
return 0;
}
void disp(double *p, int t){ for(int i=0;i<t;i++) cout << p[i] << ' ';
cout << '\n';
}
double dot(double *p, double *q){ double s;
s=(*p)*(*q);
return s;
}
This almost works. My main problem is the dot() function.
This is the vector dot product, but I can't quite get it to work. I would really like to keep the format dot(p,q) without adding any extra parameters (since I want to use this elsewhere). I was trying to find a way to write it recursively (with dot() inside dot()) but I can't think how I would get it to terminate.
So something like dot(p,q)+dot(p++,q++)+dot(p+2,q+2) for a 3D vector.
If you want to use the same code you are already using you could just modify the dot function. However the way that Cubbi has shown is really tidy and less cluttered.
1 2 3 4 5 6 7 8 9 10
double dot(double *p, double *q,int x) // x is the size of the array
{
double s=0;
for (int i =0; i<x; i++)
{
s+=p[i]*q[i];
}
return s;
}