Pointers not passing their value - c++

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
http://i.imgur.com/esF9c04.png

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)

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)

Related

I am trying to pass an DMA array and its size as an argument but it is giving an error

I am trying to pass a dynamic memory allocated array and its size to a function 'sum' but it is giving error of permissive what should I do?
#include<conio.h>
#include<iostream>
using namespace std;
int sum(int n[], int *m)
{
for(int z=0;z<*m;z++)
{
cout<<"\n the output is = "<<n[z]<<"\n";
}
}
int main()
{
int *n,*m,a; //declaration is done here**strong text**
cout<<"enter the size of array = ";
m=new int;
cin>>*m;
n=new int[*m];
for(int i=0;i<*m;i++)
{
cout<<"\n enter the "<<i+1<<" array = ";
cin>>n[i];
cout<<"\n";
}
/* for(int z=0;z<*m;z++)
{
cout<<"\n the output is = "<<n[z]<<"\n";
}*/
int sum(n,&m);//here "m" is an pointer and I am trying to pass int in a function with an array
return 0;
}
Your code should, probably, look like the following (Linux Ubuntu + gcc):
#include <iostream>
using namespace std;
int sum(int n[], int m)
{
int s=0;
for(int z=0; z<m; z++)
{
cout<<"\n array["<<z<<"]= "<<n[z]<<"\n";
s+=n[z];
}
return s;
}
int main()
{
int *n,m;
cout<<"enter the size of array = ";
cin>>m;
n=new int[m];
for(int i=0; i<m; i++)
{
cout<<"\n enter array["<<i+1<<"] value = ";
cin>>n[i];
cout<<"\n";
}
int s = sum(n, m);
cout<<"s="<<s<<endl;
return 0;
}
There is no use allocating the size of the array m dynamically. It is an ordinary int variable and can be initialized as
cin>>m;
You may also write the sum prototype in the form
int sum(int * n, int m)
It is another way of passing a 1-dimensional array as a function parameter.
Speaking frankly, these questions are the very basics of the language.
You should, probably, read something like
Dynamic memory allocation/dynamic arrays
about dynamic memory allocation and dynamic arrays and
Simple cases of std::cin usage
about the simplest cases of std::cin usage in C++.

C++ array compile

I keep getting 3 compiling errors that say "Function definition is not allowed". I am not sure on how to fix it. I keep getting it after the int main, and after the void functions. Please help!
This is the code:
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
int populateIntegerArray(int *arrayPtr, int arraySize);
void displayIntegerArray(int *arrayPtr, int arraySize);
int findMaximumInteger(int *arrayPtr, int arraySize);
int populateIntegerArray(int *arrayPtr,int arraySize)
{
for(int i=0;i<arraySize;i++)
{
cout<<"Enter value for array element "<<i<<":";
cin>>arrayPtr[i];//reading values
}
void displayIntegerArray(int *arrayPtr,int arraySize)
{
for(int i=0;i<arraySize;i++)
cout<<&arrayPtr[i]<<": arrayPtr["<<i<<"] = "<<setw(15)<<arrayPtr[i]<<endl;
}
void findMaximumInteger(int *arrayPtr,int arraySize)
{
int maximum = arrayPtr[0];
for(int i=0;i<arraySize;i++)
{
if(maximum<arrayPtr[i])max=arrayPtr[i];
}
cout<<"Maximum integer in array is: "<<max<<endl;
}
int main()
{
int n;
//reading array size
cout<<"Enter desired array size:";
cin>>n;
int *a = new int[n];
cout<<"arrayPtr = "<<a<<endl;
populateIntegerArray(a,n);
displayIntegerArray(a,n);
findMaximumInteger(a,n);
cout<<"DELETING array at arrayPtr = "<<a<<endl;
delete a;
return 0;
}
First, you are missing the last } after the definition of populateIntegerArray and before the displayIntegerArray:
int populateIntegerArray(int *arrayPtr,int arraySize)
{
for(int i=0;i<arraySize;i++)
{
cout<<"Enter value for array element "<<i<<":";
cin>>arrayPtr[i];//reading values
}
void displayIntegerArray(int *arrayPtr,int arraySize)
Then, you have the following prototype:
int findMaximumInteger(int *arrayPtr, int arraySize);
But you define the actual function as returning void (it should be int instead):
void findMaximumInteger(int *arrayPtr,int arraySize)
{
Then, in your findMaximumInteger function, you are not defining the max variable anywhere.
Functions populateIntegerArray and findMaximumInteger are declared as returning int, but actually do not return a value. You should either return an integer, or (if you intend to just output the result to console without returning a value from a function) change the functions' prototypes to returning void (not int).

Hi, Just Want to Know What This Error Means

"error C2660: 'storeInitialValues' : function does not take 1 arguments" shows up in the log of my code when I try to build. I've looked at some past errors posted here and I think it might be some kind of initialization error with either/all the usersize, v, dsize, and/or asize. I just want to see the error on the specific calling of storeInitialValues(usersize, v, dsize, asize); that's it. Thank you very much in advance.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
struct vec
{
};
struct arr
{
};
void fillArray(int A[], int size);
void storeInitialValues(int * & arr, int & asize, int & dsize, vector<int>& v, int & usersize);
int main()
{
int usersize, dsize, asize;
vector <int> v;
int * ptr = new int[10];
cout << "How many values in data structures? Please enter values greater than 20." << endl;
cin >> usersize;
while (usersize < 21)
{
cout << "Error, enter values greater than 20!" << endl;
cin >> usersize;
}
cout << "Alright, here are your numbers: " << endl;
storeInitialValues(usersize, v, dsize, asize);
}
// fillArray stores sequential, unique, integer values into an array and
// then randomizes their order
void fillArray(int A[], int size)
{
srand((int)time(0));
for (int i = 0; i < size; i++)
{
A[i] = i + 1;
}
for (int k = size - 1; k>1; k--)
{
swap(A[k], A[rand() % k]);
}
}
// storeInitialValues calls fillArray to produce an array of unique randomly
// organized values and then inserts those values into a dynamically sized
// array and a vector.
void storeInitialValues(int * & arr, int & asize, int & dsize, vector<int>& v, int usersize)
{
int * temp = new int[usersize]; // temporary array for randomized data
fillArray(temp, usersize); // get data
for (int i = 0; i < usersize; i++) // copy data into the dynamic data structures
{
add(arr, asize, dsize, temp[i]);
v.push_back(temp[i]);
}
delete[] temp; // clean up temporary pointer
temp = NULL;
}
void add(int & usersize, int & arr, int & dsize, int & temp[i])
{
}
void remove()
{
}
Nothing about your call to storeInitialValues matches the declaration. I think you might be confused thinking the names of the variables are important. That's not the case. You have to pass variables that match the type of the variables in the function declaration in the correct order, the name are irrelevant.
int * & arr is a very strange declaration. int *arr would be a pointer to an int that you could treat as an array. What exactly are you aiming for with int * &? Mixing * and & requires that you be very careful with your usage. But you are also using vector, which is a very safe way of dealing with arrays. Why not just use vectors? You also declare and allocate ptr in the main function but you don't use it nor do you delete it.

C++ function does not execute in the main section

I am having difficulties with a program that does not execute a function and i cant seem to find the problem.
This little piece of code that I'm trying to write should ask the user to enter the size of the 2d array and after that search each row and calculate the average of the rows.
It executes just fine until the calculation results come up.
The example:
Enter the size of the array: 2
2
Enter the element of the 1 row and 1 column: 10
Enter the element of the 1 row and 2 column: 20
Enter the element of the 2 row and 1 column: 50
Enter the element of the 2 row and 2 column: 20
Program ended with exit code: 0
and code of the program:
#include <iostream>
#include <iomanip>
using namespace std;
void calculate(int n, int m, int matrix[10][10], double sum, double avg[10], int k); //to calculate the average of each row
void input(int n, int m, int matrix[10][10]); //to input the requirements
void results(double avg[10],int n); //to output the results
int main() {
int matrix[10][10]; //the array
int n,m; //rows and columns entered by the user
double avg[10]; //average of the array rows, which will be calculated later
int k; //number of positive elements
double sum; //to calculate sum
input(n, m, matrix);
calculate(n, m, matrix, sum, avg, k);
results(avg, n);
return 0;
}
void input(int n, int m, int matrix[10][10]) {
cout<<"Enter the size of the array: ";
cin>>n>>m; //the real elements of the array
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
cout<<"Enter the element of the "<<i+1<<" row and "<<j+1<<" column: "; //entering each element of the array
cin>>matrix[i][j];
}
}
}
void calculate(int n, int m, int matrix[10][10], double sum, double avg[10], int k) {
for (int i=0; i<n; i++) {
k=0;
sum=0;
avg=0;
for (int j=0; j<m; j++) {
if (matrix[i][j]>0) {
sum+=static_cast<double>(matrix[i][j]);
k++;
}
}
if (k>0) {
avg[i]=sum/static_cast<double>(k);
}
}
}
void results(double avg[10], int n) {
for (int i=0; i<n; i++) { //
cout<<"Average of "<<i<<" row is equal to: "<<avg[i]<<"\n";
}
}
There are multiple problems with your code:
You ask the user for the size of your array, but you have the array defined with constant size:
int matrix[10][10];
What would happen if user entered 11? It would result in an undefined behavior. Consider using std::vector if you want to have truly dynamic arrays.
When you read your n, m values inside void input(int n, int m, int matrix[10][10]) procedure, you are making changes to the copies of those variables (i.e. they are passed by value), so, the changes are only visible to the inside of the function. When you leave the scope of that function, all changes you did to them, are lost. You need to pass those parameters by reference, i.e.:
void input(int& n, int& m, int matrix[10][10]);
That way, the compiler won't do a copy, and you will be changing the same variables from your main.
Having that in mind, you would need to change your calculate procedure in a similar way:
void calculate(int n, int m, int matrix[10][10], double& sum, double avg[10], int& k);
No need for variables n, and m to be passed by reference, since, in this case, they are input parameters, and don't need to be changed.
You are not changing n and m in main(). input() takes in the parameters by value which mean it makes a copy so the changes done in the function are local only to the function. To fix this just pass n and m by reference.
void input(int& n, int& m, int matrix[10][10])

C++ Splitting an array into 2 separate arrays

I need to write a program that takes a given array and then splits it into two separate arrays with one array's elements being the positive elements of the main array and the other's elements being the negative elements of the main array.
After doing my best with the code, I got about a million lines of errors when trying to compile it. Is there a problem with how I am deleting the three dynamically allocated arrays? What huge error is preventing compiling?
Here is my code:
#include <iostream>
using namespace std;
void count(int ARRAY[], int SIZE, int& NEG, int& POS);
void split(int ARRAY[], int SIZE, int& NEG_ARRAY, int NEG, int& POS_ARRAY, int POS);
void print_array(int ARRAY[], int SIZE);
int main()
{
int SIZE(0);
int* ARRAY;
cout << "Enter number of elements: ";
cin >> SIZE ;
ARRAY = new int[SIZE];
int x(0);
int numEle(0);
cout << "Enter list: " << endl;
while (numEle < SIZE)
{
ARRAY[numEle] = x;
numEle++;
cin >> x;
}
int POS(0), NEG(0);
count(ARRAY, SIZE, NEG, POS);
int* NEG_ARRAY;
NEG_ARRAY = new int[NEG];
int* POS_ARRAY;
POS_ARRAY = new int[POS];
split(ARRAY, SIZE, NEG_ARRAY, NEG, POS_ARRAY, POS);
cout << "Negative elements: " << endl;
cout << print_array(NEG_ARRAY, NEG) << endl;
cout << "Non-negative elements: " << endl;
cout << print_array(POS_ARRAY, POS) << endl;
delete [] ARRAY;
delete [] NEG_ARRAY;
delete [] POS_ARRAY;
return 0;
}
void count(int ARRAY[], int SIZE, int& NEG, int& POS)
{
for (int x=0; x < SIZE; x++)
{
if (ARRAY[x] >= 0)
{
POS = POS + 1;
}
if (ARRAY[x] < 0)
{
NEG = NEG + 1;
}
}
}
void split(int ARRAY[], int SIZE, int& NEG_ARRAY, int NEG, int& POS_ARRAY, int POS)
{
NEG = POS = 0;
for (int x = 0; x < SIZE; x++)
{
if (ARRAY[x] < 0)
{
NEG_ARRAY[NEG++] = ARRAY[x];
}
else
{
POS_ARRAY[POS++] = ARRAY[x];
}
}
}
void print_array(int ARRAY[], int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
cout << ARRAY[i] << " ";
}
cout << endl;
}
The code is supposed to read in the array and display a new negative and a new positive array. Thanks in advance!
There is a bunch of errors in your code. The worst one is passing the arrays by references in the declaration and definition of the split function. Change both to void split(int ARRAY[], int SIZE, int *NEG_ARRAY, int NEG, int *POS_ARRAY, int POS);, and most of the errors will be gone.
The rest is from the two lines in which you print the array in your main:
cout<<print_array(NEG_ARRAY, NEG) <<endl;
You don't want to print the function, you want to use the function to print inside it (which you do correctly). You need to change the calls to simply:
print_array(NEG_ARRAY, NEG);
And that'll make your code compile.
Hovewer there's one more error, which will make the whole app work in an improper way. In the place you input the values, you need to get the input from cin before inputting it in the array. Like this:
while(numEle<SIZE) {
cin>>x;
ARRAY[numEle] = x ;
numEle++;
}
You have the following bugs:
void split(int ARRAY[], int SIZE, int&NEG_ARRAY, int NEG, int&POS_ARRAY, int POS);
change to :
void split(int ARRAY[], int SIZE, int*NEG_ARRAY, int NEG, int*POS_ARRAY, int POS);
also the :
void split(int ARRAY[], int SIZE, int&NEG_ARRAY, int NEG, int&POS_ARRAY, int POS){..}
change to :
void split(int ARRAY[], int SIZE, int*NEG_ARRAY, int NEG, int*POS_ARRAY, int POS){..}
and
cout<<print_array(NEG_ARRAY, NEG) <<endl
cout<<print_array(NEG_ARRAY, POS) <<endl;
to :
print_array(NEG_ARRAY, NEG);
print_array(NEG_ARRAY, POS);
After fixed these bugs, it can compile and run well.
First of all, using a std::vector is almost always nicer than using dynamically allocated C arrays. You don't get the horrible mixture of pointers and square bracket array access, and you don't need to pass round extra size variables.
Secondly, the standard library has some nice algorithms to help do what you want to do. Let's assume that you write the given numbers into a vector called vec. You can then use std::partition to move all the elements less than zero to the first half of the vector, and all the elements greater than or equal to zero to the second half, like so:
inline bool less_than_zero(int a)
{
return a < 0;
}
std::vector<int>::iterator midpoint = std::partition(vec.begin(),
vec.end(),
less_than_zero);
(There are other ways of specifying the predicate, but a simple function definition like this is easiest for demonstration purposes.)
The returned iterator points to the first item in the vector which is non-negative. So now you can easily copy the values into two new vectors:
std::vector<int> negative(vec.begin(), midpoint);
std::vector<int> positive(midpoint, vec.end());
And that's it!