user5349891
user5349891

Reputation:

Pointers not passing their value

I'm trying to solve a mystery that occured while doing the assignement. The main and entry functions works just fine, but the average one doesnt. While checking if variables constant and arraysize, it seems that they do not to pass it's values like it should while I was dereferencing them.

And yes, i'm new to pointers, so any suggestions would be great.

Here's the code:

#include <iostream>
using namespace std;
void entry(int &size, int *arraysize, int &c, int *constant, int *firstArray, int *secondArray);
void average(int &size, int &c, int *arraysize, int *constant, int *firstArray, int *secondArray);
void newarray();
void output();
int main() {
    int size;
    int *arraysize;
    int c;
    int *constant;
    int *firstArray;
    int *secondArray;
    entry(size, arraysize, c, constant, firstArray, secondArray);
    average(size, c, arraysize, constant, firstArray, secondArray);
}

void entry(int &size, int *arraysize, int &c, int *constant, int *firstArray, int *secondArray) {
    cout<<"Enter the size of the array: ";
    cin>>size;
    arraysize = &size;
    cout<<"array size: "<<*arraysize<<endl;
    cout<<"Enter the constant c: ";
    cin>>c;
    constant = &c;
    cout<<"constant c size: "<<*constant<<endl;
    firstArray = new int[*arraysize];
    secondArray = new int [*arraysize];
    for (int i=0; i<*arraysize; i++) {
        cout<<"Enter the "<<i+1<<" element of the first row: ";
        cin>>firstArray[i];
    }
    for (int i=0; i<*arraysize; i++) {
        cout<<"Enter the "<<i+1<<" element of the second row: ";
        cin>>secondArray[i];
    }
}

void average(int &size, int &c, int *arraysize, int *constant, int *firstArray, int *secondArray) {
    cout<<"Array size: "<<*arraysize<<endl;
    cout<<"Constant: "<<*constant<<endl;
}

It show's me this kind of error, when program hits the average function https://i.sstatic.net/rEOzN.png

Upvotes: 1

Views: 53

Answers (2)

Camilo
Camilo

Reputation: 356

There is some errors in your code.

When you want to send values to a function/procedure and save their changes:

In C++ only:

  • For variables: When receiving int &variable and when sending send(variable)
  • For arrays: When receiving int *array and when sending send(array)

In C:

  • For variables: When receiving int *variable and when sending send(&variable)
  • For arrays: When receiving int *array and when sending send(array)

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

Modifying arguments in callee won't affect caller's local variables unless the arguments modified are reference.

Use reference as you did in int arguments.

Modify both prototype declaration and function definition like this:

void entry(int &size, int *&arraysize, int &c, int *&constant, int *&firstArray, int *&secondArray)

Upvotes: 1

Related Questions