Passing Dynamic Arrays to a function?

S

Scott Lyons

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.

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 :)

Thanks in advance!
Scott

#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <string.h>
#define NUM_STUDENTS 5

int main()
{
char buffer[81];
char *studentID[NUM_STUDENTS];
for (int i = 0; i < NUM_STUDENTS; ++i)
{
cout << "Enter the student's ID number: ";
cin.getline(buffer,81);
cout << endl;

studentID = new char [strlen(buffer) +1];
strcpy(studentID, buffer);
}


return 0;
}
 
L

Leor Zolman

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.

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.
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 :)

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 << 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 = new char [std::strlen(buffer) +1];
strcpy(arr, 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
 
S

Scott Lyons

int fill(char *arr[], int max_size)
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


Awww dang it! When I was doing the function definition, I was putting
char InputIDs(char *array);

I was leaving off the brackets after array. It should have been
char InputIDs(char *array[]);

I knew the code worked fine, but the lack of those two brackets had been
driving me nuts! Its always something simple! Two little characters and
the code doesnt work. Ahhh, thats the crazy but fun world of C++ for ya ;)

Thanks for the quick help, Leor! After I went over your code I was able to
spot my mistake, and my function is working wonderfully. Now I just have to
whip together a way to sort a multidimensional array, clean up the code, and
I'll be finished with this thing.

Thanks again!
Scott
 
J

James Moughan

Scott Lyons said:
Hey all,

Can someone help me figure out how to pass a dynamic array into a function?

Maybe, but I'm a newbie here too, so take this with a pinch of salt.
:)
My little snippet of code is below. Basically, the studentID[] array is
dynamic so it will fit any length of a Student's Name.

Hmm, no, it's a static array. It contains pointers to characters
which you then use to reference arrays, though...

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).

OK - if it needs to return it, why do you need to pass the array into
a function? Likewise, if you pass the array in, why not just full up
it's values instead of returning it? I'd take the latter approach
since it saves a new.

If you really, really want to pass in a static array then this will
work AFAICT

#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <string.h>
#define NUM_STUDENTS 5

void getIDs(char** studentID){
char buffer[81];
for (int i = 0; i < NUM_STUDENTS; ++i)
{
cout << "Enter the student's ID number: ";
cin.getline(buffer,81);
cout << endl;

studentID = new char [strlen(buffer) +1];
strcpy(studentID, buffer);
}
}

int main()
{

char* studentID[NUM_STUDENTS];

getIDs(&studentID[0]);

for (int i = 0; i < NUM_STUDENTS; ++i){
cout << studentID << endl;
delete [] studentID;
}


return 0;
}

This will copy everything to the array which is passed in. However,
it's not great code. If you want to write like that the you should
perhaps ask on comp.lang.c. ;-)

It seems a heck of a lot simpler to use the STL.

#include <iostream.h>
#include <iomanip>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iterator>
#define NUM_STUDENTS 5

void getIDs(std::vector<std::string>& studentID){

for (int i = 0; i < NUM_STUDENTS; ++i)
{
std::string buffer;
cout << "Enter the student's ID number: ";
cin >> buffer;
cout << endl;
studentID.push_back(buffer);
}
}

int main()
{
using namespace std;

vector<string> studentIDs;

getIDs(studentIDs);

copy(studentIDs.begin(), studentIDs.end(),
ostream_iterator<string>(cout, ", "));

return 0;
}

This copies everything into the studentIDs vector. It's clearer,
shorter, doesn't need memory allocation and so doesn't leak memory
like your example... Is there any particular reason why you must use
pointers and dynamic memory?

Jam
 
J

Jeff Schwab

Scott said:
Can someone help me figure out how to pass a dynamic array into a function?

Are you familiar with std::vector? It is a class template that can be
used much like a dynamically allocated array.

#include <iostream>

template< typename Array >
void print_first_two_elements ( Array const& a )
{
std::cout << a[ 0 ] << ", " << a[ 1 ] << '\n';
}

#include <vector>

int main ( )
{
int a[ ] = { -37, 500 };
std::vector< int > v( 1, -37 );

v.push_back( 500 );

print_first_two_elements( a );
print_first_two_elements( v );
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top