472,325 Members | 1,500 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,325 software developers and data experts.

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 7481
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a...
6
by: fivelitermustang | last post by:
I have two matrices allocated dynamically in both directions: matrix x and matrix v. I want to pass these matrices into a function by reference....
9
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in...
2
by: dave.harper | last post by:
I'm relatively new to C++, but have a question regarding functions and arrays. I'm passing a relatively large array to a function several thousand...
2
by: NM | last post by:
Hello all, I am supposed to do some mixed programming with c++ and fortran. I was succeeful in exchanging the 2D arrays from fortran to c++ and...
2
by: Steve Turner | last post by:
I have read several interesting posts on passing structures to C dlls, but none seem to cover the following case. The structure (as seen in C) is as...
4
by: assgar | last post by:
Hi I am stuck on a problem. I use 3 scripts(form, function and process). Development on win2003 server. Final server will be linux...
4
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level...
1
by: fahd | last post by:
Hi, I'm trying to communicate with an unmanaged c++ dll that takes two 2d float arrays, one as input with data in it and the other will have the...
0
by: tammygombez | last post by:
Hey everyone! I've been researching gaming laptops lately, and I must say, they can get pretty expensive. However, I've come across some great...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...

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.