How to pass arrays in the main func. w/ c++ - c++

#include <iostream>
using namespace std;
const int MAX = 1000;
int ArrMix[MAX];
int *ptrArrPos[MAX];
int *ptrArrNeg[MAX];
int PosCounter = 0;
int NegCounter = 0;
int r;
void accept(int ArrMix[MAX])
{
cout<<"Enter the number of elements in your array: ";
cin>>r;
for (int i = 0; i < r; i++)
{
cout<<"Enter value:";
cin>>ArrMix[i];
}
}
void process(int &i)
{
if(ArrMix[i] >= 0)
{
ptrArrPos[PosCounter] = &ArrMix[i];
PosCounter++;
}
else
{
ptrArrNeg[NegCounter] = &ArrMix[i];
NegCounter++;
}
}
void display(int &i)
{
cout<<"Your passed array is: " << endl;
cout<<ArrMix[i] << endl;
cout <<"Total number of positive integers is: "<<PosCounter<<endl;
cout<<"Your positive array is: "<<endl;
for (int i = 0; i < PosCounter; i++)
{
cout << *ptrArrPos[i] << endl;
}
cout<<endl;
cout <<"Total number of Negative integers is: "<<NegCounter<<endl;
cout<<"Your negative array is: "<<endl;
for (int i = 0; i < NegCounter; i++)
{
cout << *ptrArrNeg[i] << endl;
}
}
int main ()
{
int *i;
int a = &i;
accept(&ArrMix[MAX]);
process(a);
display(a);
system("pause>0");
}
The code you see above is a program use to create a user-defined array list of numbers. It should accept numbers from the user, display the passed array, positive numbers array and its negative numbers array. it should evaluate items, meaning separating negatives #s from positive numbers then creating an array for each. next is to use a counter to identify how many positive #s and negative #s are in each array.
I am having problems in passing the array from one function to another using pointers and calling it in the main function. so please help me?

The expression &ArrMix[MAX] returns a pointer to the integer at index MAX in the array. This index is one beyond the array, meaning you pass a pointer to beyond the array to the function which will then happily write to that memory.
Passing an array is as simple as passing any other argument:
accept(ArrMix);
You also have a problem here:
int *i;
int a = &i;
You declare i to be a pointer to an int. Then you use &i which returns the address of the variable i, in other words a pointer to a pointer to an int, and try to assign this double-pointer to a normal int variable.
It seems to me that you might want to return the number of entries is in the array from the access function, and then loop over the entries the user entered in the array and call process for each value. And then in display instead of taking the ArrMix index it should take the size and loop over that to display the ArrMix array.

Related

Variable length array c++ & No operator >> error?

going through a c++ course and was asked to create a simple program to average values in a user array
i figured id go the extra mile and learn to mess with a few additional types.
I searched online for a fix for the non variable arrays in c, and i know this is where shit hits the fan
//manually allocate the space to the array
int** MyArray = new int* [Length_Of_Array]; // i changed it to float to suit my program
For my error's im getting
ERROR IMAGE
Is there a better alternative to this (sticking to arrays as opposed to vectors) ?
MY FULL CODE
#include <iostream>
using namespace std;
//function declare
float Avg(float Array, int Length);
//Variable declare
int Length_Of_Array;
int main()
{
//Declarations
float Result{};
//User defines size of the array
cout << "Please enter the length of your array (Min 5) ";
cin >> Length_Of_Array;
//User Enters x elements into array
cout << "Please enter" << Length_Of_Array << " Digits into the array " << endl;
//manually allocate the space to the array
float** MyArray = new float* [Length_Of_Array];
//Function use
Result = Avg(MyArray, Length_Of_Array);
//Result
cout << "THE AVERAGE OF YOUR ARRAY IS " << Result << endl;
}
float Avg(float** Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
Let's take a look at this function:
float Avg(float** Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
The type of Array is float** so the type of Array[i] is float *. But you can't read a float * from std::cin and you don't need a float** for a 1D-array. (** is usually used for matrices) Since you are required to use arrays, all you have to do is to change float** to float*.
So you get float Avg(float* Array, int length) and float* MyArray = new float[Length_Of_Array];
Some other hints:
Don't forget to update the forward declaration of Avg also ;)
Don't forget to free the allocated memory if you don't need it anymore with delete[] MyArray;
You should initialize a variable with an actual value like int sum = 0; insted of int sum{};. It makes your code better readble und understandable.
The function signature in function definition and declaration doesn't match.
float** Array means array of array or a pointer to array. Besides you have problem with memory leakage.
You can simply use vector instead:
float Avg(std::vector<float>& Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
and:
std::vector<float> MyArray(Length_Of_Array);

Problem with storing 10 integers into an array C++

Ok, I'm very confused as to why this happens. All I'm trying to do is put 10 integers from input into an array. Why is this happening.
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
If you could please tell me where I'm going wrong, that would be very much appreciated. Thank you!
From how your code is written, you're only adding the user's input to the [10] element of intArray[] within that for loop you created. Additionally, any information added to the array at intArray[10] or beyond is placed out of bounds.
The only way I can really demonstrate what I mean is...
for (int i = 0; i < 10; i++)
{
std::cout<<"Enter a number:";
std::cin >> intArray[i];
}
Another thing I noticed is you're creating another array with the same name in your printData method. You should instead pass the intArray you're filling up with information to this method and use it to display your information.
The problem lies in this block of code-
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
As mentioned in other answers and comments you are storing all the values in the 10th memory slot of the array.
As per your comment
I forgot to mention, the output is just random integers and characters. EX: 00B3F724
00B3F724=> These are the memory address allocated to the array and which will hold the elements which will be inserted.
How array actually works-
float myArray[10];
The above snip creates 10 units of memory space. The units differ on the type which the array will hold. In this case it is holding float values, so each memory space will be of 4 bytes. All of these spaces have an address for lookup and other operations. All these spaces are expecting a float value to be inserted.
As you are using the loop you have to loop through the array(all the memory slots allocated to the array) and allocate a float element to each one of them and not only the last element(10th).
Effectively your for loop will become
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
Instead of intArray[10] insert values like this intArray[i]. As i will traverse through all the slots on every iteration of the loop insert a values to a slot.
Your code will look like
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
As you know if an array is declared as myArray[10], its index ranges from 0-9. Putting a value in myArray[10] will go out of bound and will produce garbage value.
In getData(float intArray[]) you are always overwriting the content of intArray[10] while it is out of bound so it is not being stored in an actual array. You should write your getData(float intArray[]) as following :
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cin >> intArray[i];
}
return 1;
}
Also in printData(float intArray[10]) you are only printing the base address of the array (i.e the name of the array gives the address of the 0th index).So the correct code would be:
void printData(float intArray[])
{
for(int i=0;i<10;i++)
{
cout << intArray[i]<<" ";
}
}
Simply change,
std::cin >> intArray[10];
to,
std::cin >> intArray[i];
What you are doing wrong:
you are storing the value at the 10th position (actually it is 11th position) again and again and the value at 10th position replaces with the new value again and also the 10th position doesn't exist in the array because the index of the array starts from 0, so your array has the index values from 0 to 9.

How to return the number of values input into an array?

At the moment, I am stumped and cannot progress on this problem. Any help or guidance would be greatly appreciated. The first part is working, however when I try to return the # of user inputs in the second part I get a Segmentation Fault. Below are the descriptions of both parts::
P2.1 Write a program consisting of main and displayArray functions. The main function declares an integer array with 10 elements and at the same time initializes them with up to 10 arbitrary values. The main function then calls displayArray function to display the contents of the array.
P2.2 Expand P2.1 with an additional fillArray function that prompts the user to enter up to 10 (size of the array) integers. Since a statically allocated array is often partially filled with values less than the actual size or storage capacity of the array (10 in our case), so the fillArray function must return a positive integer value representing the actual # of input values entered by the user.
#include <iostream>
using namespace std;
int displayArray(int arr[]);
int fillArray(int newArray[], int &inputs);
const int size = 10;
int main() {
int x, inputs = 0;
int arr[size] = {0,1,2,3,4,5};
int newArray[] = {};
displayArray(arr);
cout << "Enter .5 when finished. ";
fillArray(newArray, inputs);
cout << inputs;
cin >> x;
return 0;
}
int displayArray(int arr[]) {
for (int i = 0; i < size; i++)
cout << arr[i] << " " << endl;
}
int fillArray(int newArray[], int &inputs) {
for(int i = 0; ; i++) {
cout << "Enter an integer: " << endl;
cin >> newArray[i];
if(newArray[i] == .5) {
inputs = i + 1;
return inputs;
break;
}
}
}
You do not reserve memory for your newArray, since int newArray[] = {} will allocate an array of size 0 (actually not even defined as far as I know). So when calling fillArray, you will exceed array bounds.
Write
int newArray[10] = { 0 }
and it should at least work if you do not enter more than 10 values then.
Further, in fillArray, to not run out of bounds, I'd write...
int fillArray(int newArray[], int &inputs) {
for(inputs = 0; inputs < 10 ; inputs++) {
cout << "Enter an integer: " << endl;
cin >> newArray[i];
if(newArray[i] == 0) {
break;
}
}
inputs++;
return inputs;
}
Note further that the newArray[i] == .5 is at least misleading, since newArray is of type int and .5 is a floating point value. It will never evaluate to true, since the integral value newArray[i] will be converted to a float before comparison, and this conversion will never result in 0.5.

Change the function signature

I'm new to C++ and for now there is one thing I would want to make clear. As I'm going through the tutorial,there is this program that stores user's input into an array and gives a sum of all numbers when the user exits the program:
//PROTOTYPE DECLARATION:
int readArray(int integerArray[], int maxNumElements);
int sumArray(int integerArray[], int numElements);
void displayArray(int integerArray[], int numElements);
int main(int nNumberofArgs, char* pszArgs[])
{
cout << "This program sums values entered\n";
cout << "Terminate the loop by entering a negative number" << endl;
//store the numbers from the user into a local array
int inputValues [128];
int numberOfValues = readArray(inputValues, 128);
//output the values and the sum of the values
displayArray(inputValues, numberOfValues);
cout << "The sum is " << sumArray(inputValues, numberOfValues) << endl;
return 0;
}
int readArray(int integerArray[], int maxNumElements)
{
int numberOfValues;
for(numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
{
//fetch another number
int integerValue;
cout << "Enter next number: ";
cin >> integerValue;
if (integerValue < 0)
{
break;
}
//otherwise store the number into the storage array
integerArray[numberOfValues] = integerValue;
}
//return the number of elements read
return numberOfValues;
}
//displayArray - display the members of an array:
void displayArray(int integerArray[], int numElements)
{
cout << "The value of the array is:" << endl;
for(int i = 0; i < numElements; i++)
{
cout << i << ":" << integerArray[i] << endl;
}
cout << endl;
}
//sumArray
int sumArray(int integerArray[], int numElements)
{
int accumulator = 0;
for(int i = 0; i < numElements; i++)
{
accumulator += integerArray[i];
}
return accumulator;
}
My questions are:
Is it neccessary to declare local variables in each function (e.g. int inputValues [128];)?
Would it be correct to store the input into the arguments that were declared in the function prototype? For example, can we just store everything into integerArray[] instead of creating a storage array integerValue ?
This may look obvious but I want to understand this to avoid making mistakes in the future.
inputValues is necessary if you want to pass an array to the function.
int inputValues [128];
int numberOfValues = readArray(inputValues, 128); //passing array to function
Either way you do it is fine. So what you have is not wrong.
As noted in the comments you could also pass inputValues by reference. Which you could declare the prototype of function like this.
int readArray(int (&integerArray)[128]);
Any changes you make to the array you passed by reference will be updated when the function returns to main because you are not operating on a copy of the array anymore.
Edit:
As #Kevin pointed out, you can use a template function to get the size of the array at compile time.
template<size_t N> int readArray(int (&integerArray)[N]);
There are a lot of understanding gaps in this question.
The function parameter lists will convert their input:
If the type is "array of T" or "array of unknown bound of T", it is replaced by the type "pointer to T"
Using the implicit array to pointer assignment:
Constructs a pointer to the first element of an array.
These two together hopefully help you to see that when you declare a function like: int readArray(int integerArray[], int maxNumElements), integerArray is really just a pointer to the first element of it's first argument. You call readArray(inputValues, 128) so the parameter integerArray is equivalent to &intputArray[0].
It is not necessary and you can use global variables instead but that is bad choice in terms security and visibility etc. This program can be done few different ways but I guess what you need to learn first is difference between local and global scope, pointer/array.
In the program, memory is allocated for
int inputValues[128]; //memory allocation
Then address of that location is passed here.
int numberOfValues = readArray(inputValues, 128);
It is much more efficient this way. But it will start make more sense once you get more experience with pointer and arrays.

To write a program to remove duplicates from an array

I am working on program that remove duplicates from an array I am using three functions here: one to take the input such as the size and the number, second function to remove duplicates and return the number without duplicates and the third function just a report show the size and the new number but I am having problem I don't know in what step I think in report or phillip erreur:
In function ‘int main()’: invalid conversion from ‘int*’ to ‘int’,initializing argument 1 of ‘void report(int, int)’
#include <iostream>
using namespace std;
const int size = 100;
void phillip(int[], int & );
/* Preconditions: Array of base type in declared and int varuable declared
postconditions: the array is filled with values supllied by the user at
the keybord. the user is assked how many values they want - this value is
given to the second argument.
*/
int remdubs(int[], int noel);
/* Preconditions: An array of basetype int that has noel values.
postconditions: The number of unique elemts in the array is returned. The function removes all dubplicates inside the array.
*/
void report(int s, int d);
int main()
{
int ruby[size];
int numele, numuniq;
phillip(ruby, numele);
numuniq = remdubs(ruby, numele);
report(ruby, numuniq);
return 0;
}
void phillip(int[], int& )
{
int s;
cout << "\nHow many values you want? ";
cin >> s;
cout << "\nPlease input 10 integers, hitting return after each one \n";
for (int i = 0; i < s; i++)
{
int num;
cin >> num;
}
}
int rembups(int sapphire[], int noel)
{
for (int i = 0; i < noel; i++)
{
for (int j = i + 1; j < noel; j++)
{
if (sapphire[i] == sapphire[j])
{
for (int k = j; k < noel; k++)
sapphire[k] = sapphire[k + 1];
noel--;
j--;
}
}
}
return noel;
}
void report(int s, int d)
{
cout << "\nYou entered " << s << "distinct numbers: " << d;
}
Can't explain it better than your error:
void report (int s, int d);
this function asks for two integer values, you're passing an array to it which, with decayed functionalities, will behave like an integer pointer
int ruby[size];
report (ruby, numuniq);
I'm unsure on the behavior of your program but you should rather do something like
report(ruby[0], numuniq);
that is: access the element of the array and feed it to the function
The error is in the function report, it asks for two integer and you are passing an array and an integer instead
and again i don't think you need 2 parameters in the function report one would solve your purpose
void report(int d)
{
cout << "\nYou entered <<d<<" distinct numbers";
}
that would solve your error but i don't think you would get your desired output
Few problems with the code:
Report function should be expecting an array of integers rather than single integer
Try using human readable variable or function names
remdubs was renamed to rempubs in function definition
phillip function definition didn't have params defined properly
You have const int size but do not use it
remdups has a bug somewhere. I will leave that out as I am trying to fix other issues here.
There are better ways of finding duplicates than remdups. Please look at some other solutions.
I have fixed your code and provided it here on ideone