vector problem

Hi everybody, I want someone explain me what is wrong is this code because it's won't execute, throwing the following message during execution: main.exe has stopping working.


#include <iostream>
#include <vector>

using namespace std;

const int N = 40;

inline void sum(int *p, int n, const vector<int> toch) // inline sum functions
{
for(int i = 0, *p = 0; i < N; i++){
*p += toch[i];
}
}

int main(){
int i;
int accum = 0, *p;
p = &accum;
vector<int> data(N);
for(i = 0; i < N; ++i)
data[i] = 1;
sum(p, N, data);
cout << "Sum is " << *p << endl;
return 0;

} // end of main, end of the C++ Vector program

Thanks in advance for all your helps !
Last edited on
First, please use the code tags <>, when posting code.

Second, the compiler warns:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
using std::vector;

const int N = 7;

inline void sum( int *p, int n, const vector<int> toch )
{
  for ( int i = 0, *p = 0; i < N; i++ ){
    *p += toch[i];
  }
}

7:23: warning: unused parameter 'p' [-Wunused-parameter]
7:30: warning: unused parameter 'n' [-Wunused-parameter]

Unused parameters?

The 'n' is easy. You really don't use it anywhere.

The 'p' ...
In your main, you do declare two variables like this: int accum = 0, *p;
The 'accum' is an int and the 'p' is a pointer to int. The accum is initialized and the p is not.

In the first expression of your for loop you similarly declare two variables: int i = 0, *p = 0;
The 'i' is an int and it is initialized.
The 'p' is a pointer to int and it is initialized with 0. Null. nullptr. Invalid pointers are set to null to indicate that they point to nowhere. The asterisk denotes pointer, it is not dereference operator in this context.

Now you have problems:
1. The function local variable 'p' masks the function parameter 'p'.
2. You are accumulating to memory location 0x0.

The latter is your cause of untimely death.
Thanks a lot keskiverto, your help solve my problem, thanks again, I find and understand the problem, I was idiot.
Topic archived. No new replies allowed.