On Mon, 03 May 2004 02:35:13 GMT, "Scott Lyons" <csufsel@hotmail.com>
wrote:
[color=blue]
>Hey all,
>
>Can someone help me figure out how to pass a dynamic array into a function?
>Its been giving me some trouble, and my textbook of course doesnt cover the
>issue. Its probably something simple, but its just not popping into my mind
>at the moment.[/color]
If you're talking about a dynamic array represented by a pointer, the usual
approach is to pass the pointer to the function. The function then works
with the actual data of the array (as opposed to a copy). If you really,
really want an entire array passed to a function by value, you have to jump
through hoops. But that's not usually what you'll want.
[color=blue]
>
>My little snippet of code is below. Basically, the studentID[] array is
>dynamic so it will fit any length of a Student's Name. What I'm trying to
>do is place this chunk of code into a function, but I'm messing up the
>pointers somewhere along the way. The function would need return
>studentID[] for further use(I have 1 other dynamic arrays that uses it).
>
>If anyone with a bit more expertise then myself could take a look, it would
>be great! I'm going to keep at this thing for awhile more, so I'll check
>for replies later in the evening. I've spent a good amount of time on this
>sucker and I want to get it myself...lol. But if I dont, hopefully I can
>pick up a hint or two here :)[/color]
Okay, here's a version that abstracts out stuffing the array into a
function, and with another function to display it. I've "modernized" your
code a bit, as well, but cut some corners to keep it simple (such as
checking for a 'q' to end input, which must be in the first character
position. There are certainly more robust ways to do this in C++...):
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
const int num_students = 5;
void show_all(char *arr[], int size)
{
using namespace std;
for (int i = 0; i < size; ++i)
cout << arr[i] << endl;
cout << endl;
}
int fill(char *arr[], int max_size)
{
using namespace std;
char buffer[81];
int i;
for (i = 0; i < max_size; ++i)
{
cout << "Enter the student's ID number, or q to quit: ";
cin.getline(buffer,81);
if (*buffer == 'q')
break;
arr[i] = new char [std::strlen(buffer) +1];
strcpy(arr[i], buffer);
}
return i;
}
int main()
{
char *studentID[num_students];
int size = fill(studentID, num_students);
show_all(studentID, size);
return 0;
}
The standard disclaimer: You're better off using a std::vector for stuff
like this. But you may not have encountered vectors yet in your studies.
Good luck!
-leor
--
Leor Zolman --- BD Software ---
www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html