So I'm doing a code which sums up all elements of field but I have to use pointers:( No matter what I tried I get 1 as output. Tried same code with multiplication but still nothing... Code:
#include <iostream>
#include <cmath>
using namespace std;
float vrat=0;
int suma (int pok2, int vel22){
for(int z=0; z<vel22; z++){
vrat+=pok2;
}
return vrat;
}
int main()
{
/// 2. zadatak
int vel2;
int *vel22=&vel2;
cout<<"Unesi broj elemenata koje hoces upisati"<<endl;
cin>>vel2;
int polje2[vel2];
cout<<"Kreni unosit elemente "<<endl;
for(int z=0; z<vel2; z++){
cin>>polje2[z];
}
int *pok2=&polje2[vel2];
suma(*pok2, *vel22);
cout<<"Suma elemenata je "<<suma<<endl;
return 0;
}
Thank you!
Ah! It looks like at the very end you're printing the function suma
rather than the result. Try this instead:
int result = suma(*pok2, *vel22);
cout<<"Suma elemenata je "<< result <<endl;
I'm not sure why printing a function results in "1", but printing the actual result should work here.
I think you meant to do something like this
#include <iostream>
#include <cmath>
using namespace std;
float vrat=0;
int suma (int *pok2, int vel22){
for(int z=0; z<vel22; z++, pok2++){
vrat+=*pok2;
}
return vrat;
}
int main()
{
/// 2. zadatak
int vel2;
int *vel22=&vel2;
cout<<"Unesi broj elemenata koje hoces upisati"<<endl;
cin>>vel2;
int polje2[vel2];
cout<<"Kreni unosit elemente "<<endl;
for(int z=0; z<vel2; z++){
cin>>polje2[z];
}
int *pok2= polje2;
suma(pok2, *vel22);
cout<<"Suma elemenata je "<< vrat << endl;
return 0;
}
this line
int *pok2=&polje2[vel2];
attempts to access memory outside of the bounds of polje2. Remember arrays are zero-indexed. Let me know if this isn't what you were intending to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.