469,287 Members | 2,446 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,287 developers. It's quick & easy.

Passing Dynamic Arrays to a function?

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[i] = new char [strlen(buffer) +1];
strcpy(studentID[i], buffer);
}
return 0;
}
Jul 22 '05 #1
4 7154
On Mon, 03 May 2004 02:35:13 GMT, "Scott Lyons" <cs*****@hotmail.com>
wrote:
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[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
Jul 22 '05 #2
> 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
Jul 22 '05 #3
"Scott Lyons" <cs*****@hotmail.com> wrote in message news:<Bd*******************@newssvr29.news.prodigy .com>...
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[i] = new char [strlen(buffer) +1];
strcpy(studentID[i], buffer);
}
}

int main()
{

char* studentID[NUM_STUDENTS];

getIDs(&studentID[0]);

for (int i = 0; i < NUM_STUDENTS; ++i){
cout << studentID[i] << endl;
delete [] studentID[i];
}
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
Jul 22 '05 #4
Scott Lyons wrote:
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 );
}
Jul 22 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by fivelitermustang | last post: by
2 posts views Thread by dave.harper | last post: by
2 posts views Thread by Steve Turner | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.