I try to use array from main function that is pass into a function and into another function. Below is the simplified version of what I'm trying to do.
I can't put func2() in the main function because the code I was doing require me to do something in void func() and then apply to void func2().
#include <iostream>
using namespace std;
void func(char arr[2])
{
func2(arr);
}
void func2(char arr[2])
{
cout << arr[0] << arr[1];
}
int main()
{
char arr[2] = {1,2};
func(arr);
}
Edit:
Seems like the problem is the order of the function instead of something wrong with the array which I originally thought it was.
#include <iostream>
using namespace std;
void func2(char arr[2])
{
cout << arr[0] << arr[1];
}
void func(char arr[2])
{
func2(arr);
}
int main()
{
char arr[2] = {1,2};
func(arr);
}
Try, swap your functions around:
#include <iostream>
using namespace std;
void func2(char arr[2])
{
cout << arr[0] << arr[1];
}
void func(char arr[2])
{
func2(arr);
}
int main()
{
char arr[2] = {1,2};
func(arr);
}
The problem is that you're referencing func2 which func doesn't know anything about.
Also, try using pointers instead of copying whole arrays into functions. It's much more efficient.
Related
Is it possible to create a vector that has functions pushed back?
I've tried doing something with pointers, but it only works with functions without parameters.
For example,
#include <iostream>
#include <vector>
using namespace std;
void printInt();
int main()
{
vector<void (*)()> functionStack;
functionStack.push_back(printInt);
(*functionStack[0])();
}
void printInt()
{
cout << "function works!" << 123 << endl;
}
That works, but not what I need.
The correct version of that would be a function that has parameters: void printInt(int a) and you could call it with different values like 4 or -1 but from the vector functionStack.
It's probably more complex if the functions in the vector are with different parameters, so let's assume that every function has the same type and amount of parameters.
This:
void (*)()
is a function pointer taking no arguments. So change it to take the desired argument.
void (*)(int)
Like so:
void printInt(int x)
{
cout << "function works!" << x << endl;
}
int main()
{
vector<void (*)(int)> functionStack;
functionStack.push_back(printInt);
(*functionStack[0])(123);
}
You are correct in saying the functions must have the same type and number of parameters for this to be valid.
You basically had it already.
#include <iostream>
#include <vector>
using namespace std;
void printInt(int a);
int main()
{
// Just needed the parameter type
vector<void (*)(int)> functionStack;
// Note that I removed the () from after the function
// This is how we get the function pointer; the () attempts to
// invoke the function
functionStack.push_back(printInt);
(*functionStack[0])(42);
}
void printInt(int a)
{
cout << "function works! " << a << endl;
}
This is also a situation where std::function might be beneficial as well.
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
void printInt(int a);
int main()
{
// Similar syntax, std::function allows more flexibility at a
// lines of assembly generated cost. But it's an up-front cost
vector<std::function<void(int)>> functionStack;
functionStack.push_back(printInt);
// I don't have to de-reference a pointer anymore
functionStack[0](42);
}
void printInt(int a)
{
cout << "function works! " << a << endl;
}
Can anybody tell me what is wrong in the following code when I initialize a global array and want to print its value outside main() function
#include <iostream>
using namespace std;
int global_array[5] = {10,20,30,40,50};
cout << global_array[2];
int main()
{
cout << "Hello World!" ;
}
The error keep popping is
error: 'cout' does not name a type|
The statement cout << global_array[2]; is not a declaration (it is an expression). Only declarations are allowed outside of functions.
So, if you want to print anything outside of main function, you can only do so by having the expression within another function.
I think the problem is that the code you have that does the printing is outside of any function. Statements in C++ need to be inside a function. For example:
#include <iostream>
using namespace std;
void hello();
int global_array[5] = {10,20,30,40,50};
void hello()
{
cout << global_array[2];
}
int main()
{
hello();
cout << "Hello World!" ;
}
Before asking a question, you can search: ‘cout’ does not name a type
Thanks you.
if you want to call it from outside the main it should be in a function something like this
#include <iostream>
using namespace std;
int global_array[5] = {10,20,30,40,50};
int pre()
{
cout << global_array[2];
return 0;
}
int x = pre();
int main()
{
cout<<"Hello World";
return 0;
}
as i mentioned it on comment it can be done via c++ classes.
#include <iostream>
int global_array[5] = { 10,20,30,40,50 };
struct foo
{
foo()
{
std::cout << global_array[2] << std::endl;
}
};
foo f;
int main()
{
}
I have to use a struct array called Robot_parts[] for each part_rect struct (part_num, part_name, part_quantity, part_cost)
And through the void display function, I have to display Robot_parts[] array entirely through pointer but I don't know how, and I don't know where to declare Robot_parts[] and whether i have to put any number value inside the brackets.
So far I have:
#include <iostream>
#include <string>
using namespace std;
void display();
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
int main()
{
part_rec Robot_parts[ ] = {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
return 0;
}
void display()
{
cout<<Robot_parts[]<<endl<<endl;
}
If I also made a few other errors, please let me know. Thanks!
As stated in a comment it would be much better to use a c++ container like a std::vector or std::array.
But since your professor requires an old-style array, you could try like the code below - see the comments for explanation:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
// You have to pass a pointer (to the array) and the size of the array
// to the display function
void display(part_rec* Robot_parts, int n);
// Make a function so that you can "cout" your class directly using <<
// Note: Thanks to #BaumMitAugen who provided this comment and link:
// It makes use of the so called Operator Overloading - see:
// https://stackoverflow.com/questions/4421706/operator-overloading
// The link is also below the code section
std::ostream &operator<<(std::ostream &os, part_rec const &m)
{
// Note - Only two members printed here - just add the rest your self
return os << m.part_num << " " << m.part_name;
}
int main()
{
part_rec Robot_parts[] {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
display(Robot_parts, 3);
return 0;
}
void display(part_rec* Robot_parts, int n)
{
// Loop over all instances of your class in the array
for (int i = 0; i < n; ++i)
{
// Print your class
cout << Robot_parts[i] << endl;
}
}
The link recommended by #BaumMitAugen:
Operator overloading
I am learning classes and OOP, so I was doing some practice programs, when I came across the weirdest bug ever while programming.
So, I have the following files, beginning by my class "pessoa", located in pessoa.h:
#pragma once
#include <string>
#include <iostream>
using namespace std;
class pessoa {
public:
//constructor (nome do aluno, data de nascimento)
pessoa(string newname="asffaf", unsigned int newdate=1996): name(newname), DataN(newdate){};
void SetName(string a); //set name
void SetBornDate(unsigned int ); //nascimento
string GetName(); //get name
unsigned int GetBornDate();
virtual void Print(){}; // print
private:
string name; //nome
unsigned int DataN; //data de nascimento
};
Whose functions are defined in pessoa.cpp
#include "pessoa.h"
string pessoa::GetName ()
{
return name;
}
void pessoa::SetName(string a)
{
name = a;
}
unsigned int pessoa::GetBornDate()
{
return DataN;
}
void pessoa::SetBornDate(unsigned int n)
{
DataN=n;
}
A function, DoArray, declared in DoArray.h, and defined in the file DoArray.cpp:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
pessoa** pointer= &p;
return pointer;
}
And the main file:
#include <string>
#include <iostream>
#include "pessoa.h"
#include "DoArray.h"
#include <cstdio>
using namespace std;
int main()
{
//pessoa P[10];
//cout << P[5].GetBornDate();
pessoa** a=DoArray(5);
cerr << endl << a[0][3].GetBornDate() << endl;
cerr << endl << a[0][3].GetName() << endl;
return 0;
}
The weird find is, if I comment one of the methods above, "GetBornDate" or GetName, and run, the non-commented method will run fine and as supposed. However, if both are not commented, then the first will run and the program will crash before the 2nd method.
Sorry for the long post.
Let's look into this function:
int *get()
{
int i = 0;
return &i;
}
what is the problem with it? It is returning pointer to a local variable, which does not exist anymore when function get() terminates ie it returns dangling pointer. Now your code:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
return &p;
}
do you see the problem?
To clarify even more:
typedef pessoa * pessoa_ptr;
pessoa_ptr* DoArray(int n)
{
pessoa_ptr p= whatever;
return &p;
}
you need to understand that whatever you assign to p does not change lifetime of p itself. Pointer is the same variable as others.
I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
Voilà!
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.