Error in Pointer to array program
Sep 13, 2017 at 5:31pm UTC
There is a lot of confusion in pointers, partly because the programs in slides have errors. Please help in correcting the error in this program. The error which I get is :
C:\Users\my pc\Documents\C++\Slide8Pointer.cpp [Error] invalid types 'float*[float]' for array subscript
The C++ program is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include<iostream>
using namespace std;
int main()
{
float v[4];
float &component(float *, float );
for (float k=1; k<=4; k++)
{
component(v,k)=1.0/k;
cout<<"k=" <<k<<endl;
}
for (int i=0; i<4; i++)
{
cout<<"v[" <<i<<"]" <<v[i]<<endl;
}
}
float & component(float *v, float k)
{
cout<<"inside function k=" <<k<<endl;
return (v[k-1]);
}
Last edited on Sep 13, 2017 at 5:33pm UTC
Sep 13, 2017 at 6:43pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
double & component(double *, double );
int main()
{
double v[4];
for (double k=1; k<=4; k++)
{
component(v, k) = 1.0/k;
std::cout << "k = " << k << '\n' ;
}
for (int i=0; i<4; i++)
{
std::cout << "v[" << i << "]" << v[i] << '\n' ;
}
}
double & component(double * v, double k)
{
std::cout << "inside function \"component()\" k = " << k << '\n' ;
return (v[static_cast <unsigned >(k)-1]);
}
Sep 13, 2017 at 8:37pm UTC
Thanks. I checked, it would work fine even if float k replaced by int k
Topic archived. No new replies allowed.