473,699 Members | 2,679 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

passing dynamic 2-dimensional array to function

48 New Member
All I want to do is pass my array "p" which is a 2-dimensional string array to the function changeData()... . Can't remember how to pass that. Any ideas?

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. #include <new>
  5. #include <iomanip>
  7. using namespace std;
  10. /*
  11.     function: countRecords
  12.     params: string fileName, bool outputTF
  13.     purpose: counts records from passed file name and outputs data if bool is true
  14. */
  15. int countRecords(string fileName, bool outputTF)
  16. {
  17.     ifstream inFile;
  18.     int recordCount = 0;
  20.     inFile.open(fileName.c_str(),ios::in);
  21.     if(inFile.is_open())
  22.     {
  23.         //priming read
  24.         inFile.ignore(1000,'\n');
  25.         recordCount = 1;
  27.         //loop
  28.         while(!inFile.eof())
  29.         {
  30.             inFile.ignore(1000,'\n');
  31.             recordCount++;
  32.         }
  34.         if(outputTF == true)
  35.         {
  36.             cout << "recordCount= " << recordCount << endl;
  37.         }
  39.     }else{ cout << "File would not open!" << endl; }
  40.     inFile.close();
  42.     return recordCount;
  43. }
  45. void listData(string arr)
  46. {
  47.     cout.setf(ios::left);
  48.     cout << setw(5) << "#" << setw(5) << "ID" << setw(50) << "DESC" << setw(8) << "COST" << setw(6) << "SUPPLY" << endl;
  49.     cout << endl;
  51. }
  53. void changeData(string arr)
  54. {
  55.     listData(arr);
  56.     system("pause");
  57. }
  59. int printMenu()
  60. {
  62.     int option = 0;
  63.     cout << endl;
  64.     cout << " 1  Change Data" << endl;
  65.     cout << " 0  Exit" << endl;
  67.     cout << "Type number from left to choose operation: ";
  68.     cin >> option;
  70.     return option;
  71. }
  73. // ***************** MAIN PROCEDURE ***********************
  74. int main()
  75. {
  77.     string fileName = "data1.dat";
  78.     int c = countRecords(fileName,false);//one hundred million records MAX
  80.     string **p = new string * [c];
  81.     for(int i=0; i<c; i++)
  82.     {
  83.         p[i] = new string [4];
  84.     }
  86.     ifstream inFile;
  87.     inFile.open("data1.dat",ios::in);
  88.     if(inFile.is_open())
  89.     {
  90.         while(!inFile.eof())
  91.         {
  92.             for(int i=0; i<c; i++)
  93.             {
  94.                 for(int t=0; t<4; t++)
  95.                 {
  96.                     if(t==3)
  97.                     {
  98.                         getline(inFile,p[i][t],'\n');
  99.                         //cout << t << ": " << p[i][t] << endl;
  100.                         //system("pause");
  101.                     }else{
  102.                         getline(inFile,p[i][t],'_');
  103.                         //cout << t << ": " << p[i][t] << endl;
  104.                         //system("pause");
  105.                     }
  106.                 }//end for t
  107.             }//end for i
  108.         }//end while !eof
  110.         int option = printMenu();
  111.         while(option != 0)
  112.         {
  113.             system("cls");
  115.             if(option == 1){ changeData(p); } 
  116.             else if(option == 2){ /*function here*/ }
  118.             option = printMenu();
  119.         }
  120.     }else{
  121.         cout << "File '" << fileName << "' did not open!" << endl;
  122.         system("pause");
  123.         system("exit");
  124.     }//end if is_open
  126. // Memory Cleanup - p
  127. for (int i = 0; i < c; i++)
  128. {
  129.     delete[] p[i];
  130. }
  131. delete[] p;
  132. p = 0;
  139. //return 0
  140. return 0;
  141. }
Jan 28 '10 #1
11 3801
5,000 Recognized Expert Expert
Are you going to need to pass that by value or by reference?
Jan 28 '10 #2
9,065 Recognized Expert Moderator Expert
Read This
Jan 28 '10 #3
5,000 Recognized Expert Expert

Your response was totally off topic and has been deleted.
Jan 29 '10 #4
48 New Member
I WILL need to change the data
Jan 29 '10 #5
48 New Member
if that is how i pass it then what do i write in the function args

void changeData(WTF do i write here to accept the array?);
Jan 29 '10 #6
5,000 Recognized Expert Expert
Did you read the article Banfa posted. Especially the section about "Passing Multi-dimensional Arrays to Functions"
Jan 29 '10 #7
48 New Member
yeah and I've tried passing different ways and the problem is that I don't understand WHY to do those things so it doesn't process in my brain HOW to do what I am doing. I have experimented and failed thats why I am asking for help.
Jan 29 '10 #8
9,065 Recognized Expert Moderator Expert
You appear to be using a variable sized array of array size 4 of strings.

std:string array[N][4];

To pass that to a function you have a number of options, these are limited by the fact tat N is variable but the fact that 4 is not simplifies things a bit. To start with since we will be using 4 a lot we should define a constant with its semantic meaning, that way we can use the constant in our code and should it need to change we only have to change 1 place. I believe the type of array indexes is int so declare

const int SOME_MEANINGFUL _NAME = 4;

Since this is constant we can included it has part of the type passed to the function rather than pass the size of the second dimension as a parameter so for the first parameter of our function what we will do is write our array type leaving out the dimensions we don't know and passing a size parameter for each of the unknown dimensions

void function(std:st ring pointer[][SOME_MEANINGFUL _NAME], int size);

And actually that is it because in a function parameter list the left most set of [] is allowed to be empty. it declares a pointer to type, this is its equivalent to

void function(std:st ring (*pointer)[SOME_MEANINGFUL _NAME], int size);

Note the parenthesis are required in this syntax otherwise you declare an array of pointers rather than a pointer to an array.

It gets a little more complex if you have 2 or more unknown array dimensions.

However since you are using string you must be using C++ and if you are using C++ you should be using vectors not arrays. They handle all the memory management for you and generally make things easier.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  5. using namespace std;
  7. const int SOME_MEANINGFUL_NAME = 4;
  9. // The C++ Way
  10. void func1(vector<vector<string> >& vec)
  11. {
  12.     vector<vector<string> >::iterator outer;
  14.     for(outer = vec.begin(); outer != vec.end(); outer++)
  15.     {
  16.         vector<string>::iterator inter;
  18.         for(inter = outer->begin(); inter != outer->end(); inter++)
  19.         {
  20.             cout << *inter << endl;
  21.         }
  22.     }
  23. }
  25. // The C Way
  26. void func2(vector<vector<string> >& vec)
  27. {
  28.     vector<vector<string> >::size_type outer;
  30.     for(outer = 0; outer < vec.size(); outer++)
  31.     {
  32.         vector<string>::size_type inter;
  34.         for(inter = 0; inter < vec[outer].size(); inter++)
  35.         {
  36.             cout << vec[outer][inter] << endl;
  37.         }
  38.     }
  39. }
  41. int main()
  42. {
  43.     string fileName = "data1.dat";
  44.     int c = 20; //countRecords(fileName,false);//one hundred million records MAX
  46.     vector<vector<string> > vec;
  48.     vector<string> initialiser; // Something we can use to initialise our main vector
  50.     initialiser.resize(SOME_MEANINGFUL_NAME);
  52.     vec.resize(c, initialiser);
  54.     func1(vec);
  55.     func2(vec);
  56. }
Jan 29 '10 #9
48 New Member
Error 1 error C2664: 'changeData' : cannot convert parameter 1 from 'std::string **' to 'std::string (*)[4]' c:\users\nick\d ocuments\visual studio 2005\projects\n rsproject_001\n rsproject_001\m ain.cpp 117

Thats the error I get when doing this:

Expand|Select|Wrap|Line Numbers
  2. void changeData(string (*arr)[4])
  3. {
  4.      // why even bother getting a c++ job
  5.      system("pause");
  6. }
  8. int main()
  9. {
  11.      int c = countRecords(fileName,false);//one hundred million records MAX
  13.      string **p = new string * [c];
  14.      for(int i=0; i<c; i++)
  15.      {
  16.           p[i] = new string [4];
  17.      }
  19.      changeData(p);
Jan 31 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Cy | last post by:
I have a script that when a user selects an option from a select menu the next select menu builds dynamically with information that relates to the first menu selection. The menu builds dynamically, but the values selected will not pass. It is as if Mozilla will not recognize the menu since it was not already built with the page. Anybody have an answer? This is really keeping me from getting other stuff done .
by: Oscar | last post by:
I am looking for a way to pass an ADO recordset that has been retrieved in an ASP page to another HTML-page. Is there someone who can provide me with a small sample or a link to see how this is done? regards, Oscar
by: Peter Bailey | last post by:
Could someone please tell me how to pass criteria as if it were a parameter. I have a routine now that creates the sql string (well almost). at present the parameter is so I can pass one item ie Module M10S. Want I want to do is send 1 or more parameters ie M10S OR M10SA OR ...... The query works with one parameter can I send the dynamic sql from vba as a complete parameter string once the form calls the query? also I notice the...
by: Scott Zabolotzky | last post by:
I'm trying to pass a custom object back and forth between forms. This custom object is pulled into the app using an external reference to an assembly DLL that was given to me by a co-worker. A query-string flag is used to indicate to the page whether it should instantiate a new instance of the object or access an existing instance from the calling page. On the both pages I have a property of the page which is an instance of this custom...
by: moondaddy | last post by:
I'm writing an ecommerce app in asp.net/vb.net and need to make the pages searchable and crawlable by spiders, particularly Google's. As far as I know, if my pages's contents are mostly populated by user controls on a single page and I call these different controls by passing one or more parameters like this: myweb.com/default.aspx?MenuID=44, then the spiders aren't going to be able do to anything with this. asp.net offers lots of great...
by: spx27 | last post by:
Does anyone know the best way to handle passing a dynamic menu generated from a login from one asp.net page to another. Would it be better to recreate the menu on each page? Save the menu as a string into a session variable upon login? Any other way to do this I may be missing? This menu is part of an intranet. The user logs in, checks SQL database for folder permissions, then scans web directories for all folders which match permissions...
by: Leo J. Hart IV | last post by:
OK, here's another question for the experts: I am building a multi-step (3 steps actually) form using a panel for each step and hiding/displaying the appropriate panel/panels depending on which step you're on. This all works fine, but I ran into some trouble when I started creating controls dynamically in my code-behind file. Each panel contains a table which is filled with various radio buttons, text fields and the such which are...
by: John Smith | last post by:
I have a stored procedure that expects a month and year. There are times when I simply want to pass the current month and year (instead of, say, a querystring value). How can I pass the current month and year as the defaultText attribute value inside a <selectparameters> tag? Thank you!
by: Sandy Pittendrigh | last post by:
I have a how-to-do-it manual like site, related to fishing. I want to add a new interactive question/comment feature to each instructional page on the site. I want (registered) users to be able to add comments at the bottom of each page, similar to the way the php, mysql, apache manuals work. PUNCHLINE_A:
by: Milkstr | last post by:
is it possible to pass dynamic text through the query string command?? I know you can just pass a variale through a link eg. www.text1.com/text1.asp?username="Mike" but i want to use the dynamic text from a repaeting region something like www.text1.com/text1.asp?<%=(tempDB.fields.item("username").value%> this works kind of it shows the name in the next page, but how do i read this "?<%=(tempDB.fields.item("username").value%>" value on...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.