Sending an array between two functions C++ - c++

I am trying to send a array of 15 integers between two functions in C++. The first enables the user to enter taxi IDs and the second functions allows the user to delete taxi IDs from the array. However I am having an issue sending the array between the functions.
void startShift ()
{
int array [15]; //array of 15 declared
for (int i = 0; i < 15; i++)
{
cout << "Please enter the taxis ID: ";
cin >> array[i]; //user enters taxi IDs
if (array[i] == 0)
break;
}
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "\n";
if (goBack == 0)
update();
}
void endShift ()
{
//need the array to be sent to here
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "\n";
if (goBack == 0)
update();
}
Any help is great valued. Many thanks.

Since the array has been created on the stack, you would just need to pass the pointer to the first element, as an int*
void endshift(int* arr)
{
int val = arr[1];
printf("val is %d", val);
}
int main(void)
{
int array[15];
array[1] = 5;
endshift(array);
}
Since the array is created on the stack, it will no longer exist once the routine in which it was created has exited.

Declare the array outside of those functions and pass it to them by reference.
void startShift(int (&shifts)[15]) {
// ...
}
void endShift(int (&shifts)[15]) {
// ...
}
int main() {
int array[15];
startShift(array);
endShift(array);
}
This isn't exactly pretty syntax or all that common. A much more likely way to write this is to pass a pointer to the array and its length.
void startShift(int* shifts, size_t len) {
// work with the pointer
}
int main() {
int array[15];
startShift(array, 15);
}
Idiomatic C++ would be different altogether and use iterators to abstract away from the container, but I suppose that is out of scope here. The example anyway:
template<typename Iterator>
void startShift(Iterator begin, Iterator end) {
// work with the iterators
}
int main() {
int array[15];
startShift(array, array + 15);
}
You also wouldn't use a raw array, but std::array.

It won't work to use a local array in the startShift() function. You are best off to do one or more of the following:
Use an array in the function calling startShift() and endShift() and pass the array to these functions, e.g.:
void startShift(int* array) { ... }
void endShift(int* array) { ... }
int main() {
int arrray[15];
// ...
startShift(array);
// ...
endShift(array);
// ...
}
Don't use built-in arrays in the first place: use std::vector<int> instead: that class automatically maintains the current size of the array. You can also return it from a function altough you are probably still best off to pass the objects to the function.

void endShift (int* arr)
{
arr[0] = 5;
}

Related

Through what to call the method, if I already created constructor with initialization of array of structures?

I'm trying to call the method displayChoices, member of the class MachineManager through the object of the class. But I already have a constructor with initializing of the array of structures. How I understood when we create an object of the class compiler implicitly create a default constructor of the class.
Question: How to call method displayChoices?
#include "MachineManager.h"
using namespace std;
int main()
{
MachineManager mjp;
mjp.displayChoices();
return 0;
}
struct BrewInfo {
string* DrinkName;
double* Cost;
int* Number;
};
class MachineManager {
static const int Num_Drinks = 3; /// why it works only with static?!!!
BrewInfo* BrewArr[Num_Drinks];
public:
MachineManager()
{
*BrewArr[0]->Cost = 1.25;
*BrewArr[0]->Number = 20;
*BrewArr[1]->DrinkName = "pepsi";
*BrewArr[1]->Cost = 1.15;
*BrewArr[1]->Number = 17;
*BrewArr[2]->DrinkName = "Aloe";
*BrewArr[2]->Cost = 2.00;
*BrewArr[2]->Number = 15;
};
int displayChoices();
}
int MachineManager::displayChoices() // (which displays a menu of drink names and prices)
{
cout << 1;
int choice;
cout << "|1." << *BrewArr[0]->DrinkName << " |2." << *BrewArr[1]->DrinkName << " |3." << *BrewArr[2]->DrinkName << " |" << endl;
cin >> choice;
if (!choice || choice == 0) {
system("slc");
displayChoices();
}
else
return choice;
}
displayChoices has to print a menu in console.
You have a majo bug in your source code. You do not yet understand, how pointer work.
You are defining an array of pointer with BrewInfo* BrewArr[Num_Drinks];.
But these pointers are not initialized. They point to somewhere. Then you are dereferencing those pointers (pointing to somewhere) and assigning a value to somewhere in the memory.
This is a major bug.
The array dimensions for C-Sytle arrays must be a compile time constant.
You cannot write
int x=3;
unt array[x];
This is C99 code (called VLA, Variable length array), but not C++.
Solution for you problem:
Do never use C-Style arrays, like int array[5]. Use STL container like std::vector instead.
Do not use pointers.
This is your major problem. Define your array with BrewInfo BrewArr[Num_Drinks];. Please remove also the pointer from
struct BrewInfo {
string* DrinkName;
double* Cost;
int* Number;
};

Return the size of the hash table?

Excuse me in advance if I'm not explaining this clear..
Okay so I have declared a hash table using a vector like so:
> class HashTable{
private:
vector<string> arrayofbuckets[100];
public:
void insertelement(string input);
void deleteelement(string remove);
bool lookupelement(string search);
int tablesize();
> }; // end of class
I have also creating a menu using a switch statement to insert elements into the hash table:
> case 'I':
{
cout << " Which element would you like to insert?: ";
cin >> Element;
hash.insertelement(Element);
}
break;
It then gets passed on to this function:
void HashTable::insertelement(string input){
int hashValue = 0;
for(int i = 0; i<input.length(); i++){
hashValue = hashValue + int(input[i]);
}
hashValue = hashValue % 100;
arrayofbuckets[hashValue].push_back(input);
cout << " The element " << input << " has been put into value " << hashValue << ends;
}
Does anyone have any idea how to write a function to obtain and display the size of the table?
The best way is to keep track of the size inside functions that should initialise or modify it:
HashTable::HashTable() : size_(0) { }
void HashTable::insertelement(string input){
...do all the existing stuff...
++size_;
}
// similarly --size_ inside deleteelement...
int HashTable::tablesize() const { return size_; }
Make sure you add an int size_; data member.
Do note that bool lookupelement(string search) const; and int tablesize() const; should be const - I've inserted the keyword here so you know where to put it, and used it above when defining tablesize().
If you were really determined to avoid an extra member variable, you could also do this...
int HashTable::tablesize() const {
int size = 0;
for (std::vector<std::string>& vs : arrayOfBuckets)
size += vs.size();
return size;
}
...but most users will expect a constant-time and fast size() function: they may call it every time through their loops, so keep it cheap.

How to search array of structs for a string(name) and return info for that string(name)?

With this program, when i type in a name nothing is returned.
How would I fix this?
There are 1000 lines of info that looks like this:
114680858 19670607 Matilda Vincent MI
114930037 19471024 Desdemona Hanover ID
115550206 19790110 Xanadu Perlman ND
116520629 19630921 Alexander Hall SD
117050976 19301016 David Lamprey GA
119610646 19650202 Thomas Porlock IL
120330928 19621126 Cary Cartman NC
etc......
Code:
struct employees
{
int ss_number;//social security
int dob;//date of birth YYYY/MM/DD Ex.) 19870314=1987/03/14
string f_name;
string l_name;
string state; //state of residence
};
void read_file()//read file into array of 1000 structs
{
ifstream data("/home/www/class/een118/labs/database1.txt");
employees array[1000]
if(!data.fail())
{
int i;
for(int i=0;i<1000;i++)
{
data>>array[i].ss_number
>>array[i].dob
>>array[i].f_name
>>array[i].l_name
>>array[i].state;
}
for(int i=0;i<1000;i++)
{
cout<<array[i].ss_number>>" "<<array[i].dob>>" "<<array[i].f_name>>" "<<
array[i].l_name>>" "<<array[i].state;
}
}
}
void print_person(employees e)
{
cout<<e.ss_number>>" "<<e.dob>>" "<<e.f_name>>" "<<e.l_name>>" "<<e.state;
}
void search(employees array[])//type in name and get that persons ss_number,dob etc...
{
string first;
string last;
cout<<"Enter name";
cin>>first>>last;
for(int i=0;i<1000;i++)
{
if(array[i].f_name==first && array[i].l_name==last)
{
print_person(array[i]);
}
}
}
void main()
{
employees array[10];
read_file();
search(array);
}
// ...
There are two arrays. One is in main, the other is in read_file. They have the same name but are different sizes.
The array in read_file has no relationship to the array in main. You passed the array to search but not to read_file. I suggest you pass the array to read_file by reference and remove the array declaration in read_file.
Better yet, eliminate the array and use std::vector. It would be std::vector<employees>.
Edit 1: Searching the array
In your search function you will need to pass two additional parameters: array capacity and the number of records in the array. If you used std::vector<employees>, you could get the number of employees in the array by:
number_of_employees = array.size();
The for loop would use iterators:
std::vector<employees>::const_iterator iter;
for (iter = array.begin(); iter != array.end(); ++iter)
{
// process array slot by dereferencing it:
employee e = *iter;
cout << e << "\n"; // This could happen if you overloaded operator <<
}
Otherwise, with an array, your loop would look like:
void search(employees array[], unsigned int capacity, unsigned int employees_in_array)
{
for (unsigned int i = 0; i < employees_in_array; ++i)
{
cout << array[i];
}
}
A nice improvement is that this search function doesn't hardcode the size. So you can change the size from 10 (in main) to 1000 without modifying the search function.
If you sort your container, you can use a binary search.
See: std::binary_search, std::find, std::lower_bound, std::upper_bound

Run time error for dynamic memory allocation in C++

I am a newbie for OOP concepts and while trying to solve Project Euler Problem 7, to find 10001th prime number, I tried to do it using a class but encountered 2 major errors.
instantiating the class prime_n
initializing its argument
I have posted the code here for reference:
#include<iostream>
#include<cstdio>
using namespace std;
class prime_n
{
int j,k;
int n;
int *store;
public:
prime_n(int num)
{
n=num;
store[n];
}
static int isPrime(int j)
{
for(int i=2;i*i<=j;i++)
{
if(j%i==0) return 0;
}
return 1;
}
void find_n()
{
for(int i=0;i<n;i++)
{
store[i]=0;
}
store[0]=2;
j=3;
k=1;
while(store[n-1]==0)
{
if(isPrime(j)) store[k++]=j;
j+=2;
}
}
int get_num()
{
int value=store[n-1];
return value;
}
};
int main()
{
int num, req_num;
printf("Enter the position at which prime number is to be found ");
scanf("%d",&num);
printf("\nnumber = %d",num);
prime_n p = new prime_n(num);
req_num = p.get_num();
printf("The required prime number is %d\n",req_num);
return 0;
}
It would be a great help if someone could help me figure out where I am actually going wrong. Thanks a lot in advance!
Use
prime_n p(num);
or (not recommended in this particular case)
prime_n * p = new prime_n(num);
// some other code
req_num = p->get_num(); // note the -> operator replacing . in case of pointers
delete p;
The first case declares p on stack and it is automatically deallocated when the program leaves the scope (main function in this case)
The second one allocates space on heap and p is the pointer to it. You have to deallocate the memory manually.
As for your second question, the C++ way would be
#include <iostream>
...
int num;
std::cout << "Enter the position at which prime number is to be found "
std::cin >> num;
std::cout << std::endl << "Number = " << num << std::endl;
You provide a constructor:
prime_n(int num)
{
n=num;
store[n];
}
I think you are under the impression that store[n] creates an array with n elements, but that is not so; it attempts to access the (n+1)th element of an an array. Since store does not point anywhere (we are in the constructor, after all), the program crashes.
You probably want to write store = new int[num] instead.
And then I cannot see any call to find_n() originating from get_num() which is called in main(), so that your program would for now just return a random value.

A function is outside main,it requires use of a variable how do use it?

My function is outside main()
it's this
void Ydisplay(int D1[])
{
for(int i=0;i<a;i++)
{
cout<<"\t<<D1[i];
}
the array D1 is a dynamic array
the error is 'a' is undefined it's taken from user so it has to be in main..
but is there any other option?
You have to pass the array size along as a function parameter:
void Ydisplay(std::size_t len, int D1[])
{
for (std::size_t i = 0; i != len ;++i)
{
std::cout << '\t' << D1[i];
}
}
In C++, you would use a std:vector<int>, though.
void Ydisplay(std::vector<int> const & D1)
{
for (int n : D1)
{
std::cout << '\t' << n;
}
}
a is not know to function Ydisplay() it is local to main(), Pass value a from main.
change function syntax as:
void Ydisplay(int D1[], int a)
^ add
A syntax error, missing ":
cout<<"\t" <<D1[i];
// ^ added
Have your function in this way.,
void Ydisplay(int D1[])
{
cin >> a; //Remove getting input from main()
for(int i=0;i<a;i++)
{
cout<<'\t'<<D1[i];
}
I think you need to understand what you are trying to do. In this particular code, You are trying to print elements that are in the array D1. So you print the element starting from D1[0] to D1[n]. You use the for loop to traverse through each element in the array D1. int i starts at i = 0 to the last element which is i < sizeof(D1)/sizeof(int). You don`t need variable a, it make no sense with what you are trying to do. To print on each line try: cout << D1[i] << endl;