C++: Make an array from main() available in another funtion - c++

I am trying to create a C++ program which stores many names linked to a numeric value, and can alter the numeric value when the name is entered. My question is: if I create an array in the main function, can it be accessed from another function? And if so, what should be done for that?
Attaching code (part of it)
#include <iostream>
#include <fstream> //required as input\output is from\to file
#include <string>
using namespace std;
int name_checker (string input);
int main()
{
int cases;
cin >> cases;
string names[cases]; //this is the array.
int i=0;
while (i<cases)
{
cin >> names[i];
i++;
}
}
int name_checker (string input);
{
//i want the data stored in above array to be availible here. possible?
}

Yes, possible. Pass the array as an argument to the function.
Change the function as -
int name_checker (string input[]);
And pass the array to the function -
name_checker(names);
Note: Changing the values in the function will also affect the original values.

You should consider using a class.
So you can make the array a field (as πάντα ῥεῖ suggested you should consider using a vector ) and name_check a member function.

Related

No matching error operator error in string input?

I am learning about vector pairs, mostly I can take other datatypes easily but while taking string as input it always shows no matching operator>> error at the cin>>s statement, I am attaching a small snippet of the code (its incomplete though for purpose)-
#include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
unsigned int N;
cin>>N;
vector <pair<int,string>> v(N);
for(unsigned int i = 0;i<N;i++)
{
string s[200];
cin>>s;
v[i].make_pair(i+1,s);
}
}
return 0;
}
Declaring an array for storing a single string does not make sense here. For your purposes you can simply declare a normal string variable as:
for(unsigned int i = 0;i<N;i++)
{
string s;
cin>>s;
v[i].make_pair(i+1,s);
}
You have basically made an array of string by using the statement
string s[200];
Taking an input in s is basically meaningless here.
You would have to take an input in a particular index of s.
Something like cin>>s[0]
Another error is when you make a pair, the type you have specified for the pair is <int,string>. The pair you make here will be <int,string*>

What happens to a parameter if it is passed twice? Once by value and once by reference? Will it be modified or not?

#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("BAC.TXT");
void eval(int a, int b, int &rez)
{
rez = a + b;
}
int main()
{
int nr;
int s;
fin >> s;
while (fin >> nr)
eval(s, nr, s);
cout << s << '\n';
return 0;
}
So I have this code snippet. I am reading numbers from a file and keeping track of their sum using a given function called “eval”. I know it could be considered bad code to pass a parameter twice (in such a given instance) rather than using another variable (not sure, though, if it is bad code or not, in my case). My problem is: will it change the value of variable s? Again, I am passing it once by value and once by reference! I have written the code on my PC and it does change the value of s. Now my question would be: why? If I am asking this in a right way: what happens “in the background”?
The fact that a is a copy of s is actually a red herring. Maybe that caused your confusion, but its just a copy. Consider that you could call the function like this
auto temp = s;
eval(temp,nr,s);
to get the exact same result. Inside the function rez is a reference to s, hence modifications on it will be reflected on s in main. In other words, rez is an alias for s, while a has no relation whatsoever to s, they just happen to hold the same value.
This question is related to the behavior of functions parameters and reference/pointers.
When you pass a value to a function, it copies the value you give to a local variable inside the function.
in your case, when you pass 's', it copies it to 'a' like if you would do it in your main: int a = s (this is what is going on)
The same applies to the reference. when you pass 's' to the third parameter, it does this:
int &rez = s
When you pass it by reference, it is sort of taking the address of the variable instead of the value itself and copying this address to a local variable that is already dereferenced. (pointer stuff)
So the value is changed.
See the video related to pointers and then reference on 'the Cherno Project' youtube channel for better comprehension of the subject:
Pointers
References
Short answer: Yes, s will be changed.
Long answer: Let me rewrite your code snippet a little bit to illustrate what is happening with the function parameters during a call:
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("BAC.TXT");
void eval(int a, int b, int &rez)
{
rez = a + b;
}
int main()
{
int nr;
int s;
fin >> s;
while(fin >> nr) {
int a = s;
int b = nr;
s = a + b;
}
cout << s << '\n';
return 0;
}
So, basically, a and b are just copies of s and nr respectively. However, res is s.
IMO, this is what I would expect :
Copy s to a new var l_S.
Copy nr to a new var l_Nr.
Copy &s to new var l_Ptr.
Add l_Nr and l_S.
Save the result in *l_Ptr.

Passing a variable into an initialization of an array as a reference in a function parameter

I've been trying to learn C++ recently, and doing some hacker rank introductory tasks. I am attempting to do the https://www.hackerrank.com/challenges/deque-stl challenge, but I am very unfamiliar with c++ syntax and uses of their base "array". If I would prefer, I would at the very least use std::array (although I understand that is nothing but a zero overhead wrapper of the default C array).
My problem is this:
#include <iostream>
#include <deque>
#include <vector>
#include <array>
#include <typeinfo>
using namespace std;
void printKMax(int (&arr)[n], int n, int k){
//Write your code here.
deque<int> d(arr);
cout << arr[3];
for(int i:d) {cout <<i;}
}
int main(){
int t;
cin >> t;
while(t>0) {
int n,k;
cin >> n >> k;
int i;
int arr[n];
for(i=0;i<n;i++)
cin >> arr[i];
printKMax(arr,n, k);
t--;
}
return 0;
}
I am trying to pass the arr into printKMax, and receive it as a reference.
The error I am receiving is:
!‘arr’ was not declared in this scope
!‘n’ was not declared in this scope
!variable or field ‘printKMax’ declared void
!expected primary-expression before ‘int’
!expected primary-expression before ‘int’
of which if I use a constant int, eg "5", arr[5], it passes through.(passing arr[5] in the function call too). But if I replace with n, it doesn't work.
That is, at the moment, it is printKMax(arr,n,k) at the function call [not the definition], and I see no reason to add the arr[n] here (as it is already implicit in the array it is declared as: int arr[n]). I am trying to pass it as a reference, without it decaying into a pointer. I have messed around with passing it as *arr too, but with no success.
I read online its important to keep it as (&arr)[100] or something along those lines, but here I have (&arr)[n], and it is out of scope. I would love to just write (&arr)[], but alas I get this error instead:
parameter ‘arr’ includes reference to array of unknown bound ‘int []’
Thanks in advance! Also, is this only a problem with arrays? If I start using and and such data structures from eg the boost library, will I encounter similar problems?
PS: ignore the deque code, I was just playing around, trying to initialise it with the same elements as the array I am passing. It is probably incompatible since one is std:: and the other is default array unfortunately...?

C++ Dumping stack trace to *.exe.stackdump

Was writing some code for an assignment to take integers as input and place them in an array to be printed.
I'm cleaning up all of my pointers as far as I can tell but I keep getting the runtime error:
1 [main] new 3444 cygwin_exception::open_stackdumpfile: Dumping stack trace to new.exe.stackdump
body of code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int array[10];
int * p = array;
int *readNumbers()
{
int i=0;
for(i=0;i<10;i++)
{
string number;
int numb;
cout << "enter digit " << i << " of 10" << endl;
getline(cin, number);
istringstream (number) >> numb;
array[i]=numb;
}
return p;
delete p;
}
void printNumbers(int *numbers,int length)
{
int i;
for(i=0;i<length;i++)
{
cout << i << " " << *(numbers+i) << endl;
}
}
and the main calling code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
extern int *readNumbers();
extern void printNumbers(int *,int);
int main()
{
int * q = readNumbers();
printNumbers(q,10);
delete q;
return 0;
}
So just looking for a solution to the stack dump...
Also I'm sure the method I used to apply the string number returned by cin to the values contained in array[10] is not what the question was looking for so any notes on that would be great.
Thanks
It is not a good practice to return a pointer to a memory allocated inside a function, in this case, you are not even allocating it inside a function, you have done it in a global space.
It is a good practice to activate all your warnings during the compile, even treat them as error when you are doing an assignment.
As a tip, you can allocate the memory in your main function and then pass the pointer to the readNumbers function.T This way it remains inside the same scope and it is easier to manage.
also, the same way you pass the lenght of the array to the printnumbers function you should pass it to the readnumbers one instead of hardcoding it.
Your delete are invalid, you can only delete something you've allocated with new.
The first one is harmless because it's after a return, so never executed (BTW you should look at compiler warnings).
The second one might produce your crash.
Also I'm sure the method I used to apply the string number returned by cin to the values contained in array[10] is not what the question was looking for so any notes on that would be great.
That's OK. What's dubious is spreading the size of the array everywhere, what happens if you want to change it ?

Structures and functions(passing by reference)

Please guide me on this code, I want to store list of 5 data using array and function, this is a piece of code of mine, but this is giving me an error ("33"):
Cannot convert `ABC (*)[5]' to `ABC*' for argument `1' to `void pass(ABC*)'
Code:
#include <iostream>
using namespace std;
struct ABC{
char name[20];
int phone;
char address[20];
};
void pass(ABC *abc){
for(int i=0; i<5;i++){
cout<<"Enter name"<<endl;
cin>>abc[i].name;
cout<<"Enter phone"<<endl;
cin>>abc[i].phone;
cout<<"Enter address"<<endl;
cin>>abc[i].address;
}
}
int main()
{
ABC abc[5];
pass(&abc);
system("PAUSE");
return EXIT_SUCCESS;
}
You can use pass(&abc[0]); or pass(abc); to get a pointer to the first element in the array. Otherwise if you use &abc alone you get a pointer to a whole array[5] not the elements inside the array.
Arrays are not pointers. But they can decay to pointers when you are doing function calls.
So you can pass your array like this:
pass(abc);