Structure pointer to function? - c++

I am trying to pass a structure I created in a function to another function so basically what im trying to do is dynamically create the amount of structures needed the amount of structures is in a text file so in the text file there would be a number like 5 and and 5 data sets. I want to pass the structures I created in my function to another function. I started programming a few months ago so forgive me if there is a simple solution or if this question has been asked.
struct graph
{
int Max,Min,index;
double dataArray[300];
};
void readfile()
{
int amount;
char tmpSTR,nmbrGraph;
ifstream myFile("data1.txt",ios::in);
myFile>>amount;
myFile>>tmpSTR;
myFile>>nmbrGraph;
graph* Data = new graph[amount];
for(int j=0;j<nmbrGraph;j++)
{
for(int i=0;i<299;i++)
myFile>>Data[j].dataArray[i];
}
//hOW WOULD I PASS THE STRUCTURE "DATA" TO THE FUNCTION anotherFunction?
}
void anotherFunction()
{
for(int i = 0;i<300;i++)
cout<<Data[scroll].dataArray[i])<<endl; /*Error here! scroll being an
integer declared globally*/
}

Pass the graph* pointer by value or reference to anotherFunction as an argument. Also, it is important to include the number items, as that was determined by reading the file and not knowable beforehand.
// by value
void anotherFunction(graph* Data, int amount);
// by reference
void anotherFunction(graph*& Data, int amount);

Related

Trouble passing a whole structure array to a function

I'm sort of new to C++ and programming in general. I'm making a pokemon remake of the old gameboy version for fun, and I'm having trouble passing a whole structure as an arguement.
This is a shortened version to highlight the problem I'm having:
struct Enemy_Pokeman
{
string opp_name;
int num_pokeman;
int pokeman_LVL;
};
void pl_Pokeman(Enemy_Pokeman);
void pokeman_data(string opp_name, int num_pokeman, int pokeman_ID[], int pokeman_LVL[],
int purpose)
{
Enemy_Pokeman enemypokeman[num_pokeman];
enemypokeman[0].opp_name = opp_name;
enemypokeman[0].num_pokeman = num_pokeman;
for(int i=0; i<num_pokeman; i++)
enemypokeman[i].pokeman_LVL = pokeman_LVL[i];
pl_Pokeman(enemypokeman); //Function call - Codeblocks detects error
//on this line
}
void pl_Pokeman(Enemy_Pokeman enemy)
{
cout << endl;
}
Sorry if this doesn't make sense, I didn't want to post the entire thing, so I chopped it up a bit.
The problem is that it won't accept Enemy_Pokeman as an arguement.
Function pl_Pokeman only takes Enemy_Pokeman type while you passed in an array of Enemy_Pokeman
You update pl_Pokeman function to take array as input:
void pl_Pokeman(Enemy_Pokeman enemy[], int arraySize);
Or
template<typename T, size_t N>
void pl_Pokeman(Enemy_Pokeman (&enemy)[N])
you're passing to your function whole array of Enemy_Pokemans, not just one element. function expects one element only. also, you're creating that array within a function, so it's a local variable. if function pokemon_data returns, that array will be destroyed.
For Single structure-
When you are passing the structure as a argument, you should pass with & operator.
pl_Pokeman(&enemypokeman); // Fix 1
While catching it you need to catch it with Structure pointer.
void pl_Pokeman(Enemy_Pokeman *); // Fix 2
For Array of structure-
pl_Pokeman(&enemypokeman,size); // pass it with size
while catching it
void pl_Pokeman(Enemy_Pokeman (*)[], int );

Accessing a passed array of structures in C++

I'm learning C++ by reading forums and books so I'm kind of new to the programmer's world.
So please don't hesitate to improve my code because I'm eager to learn !
I'm having a problem to access an array of structure that I passed to a function.
Here's my code :
struct Comber
{ double real;
double im;
double mod;
};
int main (void)
{
struct Comber *Nmbr=NULL; //Nmbr Initialised for passing to Read where it's re-declared
int N;
Read(Nmbr, N);
Module(Nmbr, N);
}
void Read (Comber *Nmbr, int &N)
{
cout<<"\nHow many of those numbers do you have ?\t";
cin>>N;
Nmbr = new struct Comber [N];
for(int i=0;i<=N;i++)
{
cout<<"#"<<i<<"\nreal :\t";
cin>>Nmbr[i].real;
cout<<"img :\t";
cin>>Nmbr[i].im;
cout<<"-----"<<endl;
}
}
void Module (Comber *Nmbr, const int &N)
{
for(int i=0;i<N;i++)
{
//Here's where my problem is at.
Nmbr[i].mod=sqrt(pow(Nmbr[i].real,2)+pow(Nmbr[i].im,2));
}
}
I get an access violation because there's either no data stored or I'm looking at the wrong place. (right ?)
So I'm wondering whether the mistake is in Read or in Module and what actually is.
Thanks for looking into it !
If you want to change the value of the Nmbr pointer, you need to pass it by reference or pointer, not by value. Like this:
void Read (Comber *&Nmbr, int *N)
With your code Nmbr in the main is not chaged.

Using global variable for array size in class

I want to define dynamic array h of size size and later in other functions, modify and use it as here:
class definition:
static int size=10;
class hash{
public:
string h[size];
hash();
void resize();
void operations();
void print();
};
hash::hash()
{
h[size-1]="nikhil"; //size=10 now.
}
/*Defining `h` as `string* h=new string[size];` is not working.
My compiler (MinGW on Windows 7) show error: dynamic allocation is not allowed by default*/
// resizing the array
void hash::resize( )
{
string temp[2*size];
for(int i=0;i<=size;i=i+1)
{
temp[i]=h[i];
}
size=2*size;
h=temp;
}
void hash::print()
{
for(int i=0;i<size;i=i+1)
{if(!h[i].empty())
{cout<<"h["<<i<<"]="<<h[i]<<endl;}
}
}
int main()
{
hash p;
p.resize();//now size should change to 20.
p.print();
}
Where is the problem is it defining the size variable or in resizing the array?
Use std::vector if you need arrays of dynamic size.
class hash {
public:
std::vector<std::string> h;
hash();
void resize();
void operations();
void print();
};
hash::hash() : h(10) {
h[9] = "nikhil";
}
void hash::resize() {
h.resize(2 * h.size());
}
Though note that std::vector does resizing for you automatically if you add new elements using push_back. Also note that the standard library has hash table data types already (std::unordered_set and std::unordered_map), so you don’t have to write them yourself.
I do not know C++ but you haven't exactly told what is going on.
But the way your resize() method is working is the for loop goes through 2*the size of H which will cause a problem.
When you loop through 2*size it is trying to loop through more items than what you actually have in the original array. you have to loop through the original array size.
for(int i = 0; i < h.size(); i++)
{
temp[i] = h[i];
}
I can barely see the comments in your code they are too light for me so I didn't see them.
But to explain a little better i guess, lets say original array is size 5 your new one is size 10 when you loop through 10 items you dont have 10 items in the original array so you'll get errors when trying to access them.

1-d combined with 2-d array. Need functions calls for within main

I have a 1-d array and a 2-d array. I have them both in a function that I am using to read in information from a .txt file.
I have my arrays all set up and my functions set up correctly to my knowledge I just cannot figure out how to actually call the function that has 2 separate arrays in it. Here is the relevant information, please just let me know what I need to enter in main to call the functions. Thank you!
void getSales(double[][QUARTERS], int[]); // places sales figures into the array
void printSales(double[][QUARTERS], int[]); // prints data as a table
void printTableHeading(); // prints table heading
int main()
{
double sales[YEAR_COUNT][QUARTERS]; // 2D array to hold the sales transactions
int years[YEAR_COUNT]; // 1D array to hold the years
return 0;
}
void printTableHeading()
{
}
void getSales(double salesTable[][QUARTERS],int yearArray[])
{
}
void printSales(double salesTable[][QUARTERS], int yearArray[])
{
}
int main(
{
getSales(sales, years); // Will call your get sales function
printSales(sales, years); // Will call your print sales function
}

Need help templatizing structure accessed by multiple threads

The problem requires implementing a ring buffer into which a producer writes and from which a consumer reads. I have done this for a data type. I want to extend this so that it will work for any primitive data type but have not been able to figure out a good way to do this. I want the program to take inputs from the command line like so "program_name data_type size_of_buffer".
I could templatize the buffer.start pointer and pass the data type around but I don't know of a way to assign the data type name to a variable. Anyone have any ideas?
struct buffer{
int * start;
int size;
}buffer;
int * producer=NULL;
int * consumer=NULL;
bool donewriting;
bool sleeping;
void *mywrite(void *);
void *myread(void *);
void *mywrite(void * ){
do{
cout<<"In Thread 1"<<endl;
static int x=0;
*producer=x;
cout<<"Write thread: wrote value "<<x<<" into buffer"<<endl;
producer++;
if(producer==buffer.start+10)
{ producer=buffer.start;
donewriting=true;
}
if(x==5)
{
cout<<"Thread 1 going to sleep"<<endl;
Sleep(2000);
}
x++;
} while(producer!=buffer.start);
}
void *myread(void *){
while(!donewriting)
{ //cout<<"In Thread 2"<<endl;
if(consumer<producer)
{ cout<<"Read thread: read value "<<*consumer<<" from buffer"<<endl;
consumer++;
}
}
}
int main()
{
buffer.size=10;
buffer.start=new int(10);
producer=buffer.start;
consumer=buffer.start;
donewriting=false;
cout<<"In main"<<endl;
pthread_t writeThread,readThread;
pthread_create(&writeThread,NULL,mywrite,NULL);
pthread_create(&readThread,NULL,myread,NULL);
pthread_join(writeThread,NULL);
pthread_join(readThread,NULL);
return 0;
}
Unfortunately, your goal is not possible given the scenario you have described. Internally, C++ programs compile templated code for each datatype used with the template. In other words, if you have a templated function x() and you call
x<int>();
x<float>();
the compiler will produce two copies of the templated function: one that uses the int datatype and another that uses the float datatype. Before you call the function, no code is produced at all. Therefore, you cannot build the program and pass arbitrary data types to it.
Of course, if the command-line call is only intended as a test for the code, and you'll use it in a library in future, you're ok - but you'll still have to specify the type you're using in your code.
The current way you're doing this, using void * is probably the best way.
It might be better to specify the size in bytes of the type you wish to use, rather than the specific type itself. As long as your final producer and consumer share knowledge of the type in question, you'll be fine.