473,763 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to return an array from a sub-routine.

Neo
Dear All,
I want to know how a subroutine should return an array of values to
the main program.
From the main program, I call a sub-routine 'get_sql' which then
fetches data from oracle db using oci8 routines. The output resides in
a structure defined within the sub-routine. Now I want this structure
to be returned to main program so that I can assing output data to
variables in main program and do some manipulation. Can any body guide
me about how to do it.

I am a newbie and have never played with structures or string arrays.

Thanks in advance.

Take care
Rizwan
Nov 13 '05 #1
6 6612
On 1 Dec 2003 03:52:40 -0800, in comp.lang.c ,
ri**********@ho tmail.com (Neo) wrote:
Dear All,
I want to know how a subroutine should return an array of values to
the main program.


FYI C programmers don't use the word "subroutine ", in C its called a
function.

To return an array or struct from a function, pass a pointer to the
object into the function
struct stype s;
char a[12];

void dosomethingtos( &s );
void dosomethingtoa( &a );

You can also di it by using a static or global variable, but this is a
highly dangerous technique and makes your code non-threadsafe and
non-reentrant. For work on modern OSes this is a Bad Idea.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #2
Mark McIntyre <ma**********@s pamcop.net> wrote in
news:o8******** *************** *********@4ax.c om:
On 1 Dec 2003 03:52:40 -0800, in comp.lang.c ,
ri**********@ho tmail.com (Neo) wrote:
Dear All,
I want to know how a subroutine should return an array of values to
the main program.


FYI C programmers don't use the word "subroutine ", in C its called a
function.

To return an array or struct from a function, pass a pointer to the
object into the function
struct stype s;
char a[12];

void dosomethingtos( &s );
void dosomethingtoa( &a );

You can also di it by using a static or global variable, but this is a
highly dangerous technique and makes your code non-threadsafe and
non-reentrant. For work on modern OSes this is a Bad Idea.


Or just put it in a struct like we've mentioned countless times before.

struct WrapArr
{
int arr[1024];
};

struct WrapArr foo(struct WrapArr s)
{
memset(s.arr, 0, sizeof s.arr);

return s;
}

int main(void)
{
struct WrapArr arr;
struct WrapArr brr;

brr = foo(&arr);

return 0;
}

--
- Mark ->
--
Nov 13 '05 #3
> I want to know how a subroutine should return an array of values to
the main program.
From the main program, I call a sub-routine 'get_sql' which then
fetches data from oracle db using oci8 routines. The output resides in
a structure defined within the sub-routine. Now I want this structure
to be returned to main program so that I can assing output data to
variables in main program and do some manipulation. Can any body guide
me about how to do it.


What you want to do is have your subroutine return a pointer to an
array/structure. I don't know enough about your needs, but you may
want to consider creating an array of pointers to values or array of
pointers to structures if the size of the resulting value lengths from
your queries is not always the same (if you are pulling var char
fields for instance).

Here is a basic outline of the idea:

(Assumes function returns a pointer to a structure populated by
get_sql)

struct sql_result { int val1; char * val2; ...};

struct sql_result * sql_get ( your arguments);

int main (void) {
struct sql_result * sql_res_ptr; /* declare pointer to structure
*/
...
sql_res_ptr = sql_get ( your args);
value1 = sql_res_ptr->val1; /* Retrieve values, value 1 is int in
this example */
value2 = sql_res_ptr->val2; /* value2 is type char * here */
...
}

struct sql_result * sql_get ( your args ) {
...
static struct sql_result sql_res; /* Not thread safe */
/* Do struct populating here */
sql_res.val1 = query_db_for_va l1(blah);
sql_res.val2 = query_db_for_va l2(blah);
return (&sql_res);
...
}

The basic idea is to have your sql_get function set aside storage for
your information, populate with your query results and pass back a
pointer to the information. Note that in this example, I used a
static structure so the information your pointer points to will change
the next time this function is called. You could also have the
sql_function use malloc to dynamically allocate memory and then make
it the responsibility of the caller to free the memory when no longer
needed, or you could make the caller allocate the memory and pass the
location of the allocated memory to the function for it to use. If
you are dealing with variable length data, it might make the most
sense to have the function allocate the memory and the caller free it.

Hope this helps,

Rob Gamble
Nov 13 '05 #4
"Mark A. Odell" <no****@embedde dfw.com> wrote in message
news:Xn******** *************** *********@130.1 33.1.4...
Mark McIntyre <ma**********@s pamcop.net> wrote in
news:o8******** *************** *********@4ax.c om:
On 1 Dec 2003 03:52:40 -0800, in comp.lang.c ,
ri**********@ho tmail.com (Neo) wrote:
Dear All,
I want to know how a subroutine should return an array of values to
the main program.
FYI C programmers don't use the word "subroutine ", in C its called a
function.

To return an array or struct from a function, pass a pointer to the
object into the function
struct stype s;
char a[12];

void dosomethingtos( &s );
void dosomethingtoa( &a );

You can also di it by using a static or global variable, but this is a
highly dangerous technique and makes your code non-threadsafe and
non-reentrant. For work on modern OSes this is a Bad Idea.


Or just put it in a struct like we've mentioned countless times before.

struct WrapArr
{
int arr[1024];
};

struct WrapArr foo(struct WrapArr s)
{
memset(s.arr, 0, sizeof s.arr);

return s;
}

int main(void)
{
struct WrapArr arr;
struct WrapArr brr;

brr = foo(&arr);

----------------^---
To be consistent with declaration, it should be
brr = foo(arr);
Though I prefer passing pointer(s) in this case
(as Mark McIntyre suggested), not structs themselves.
return 0;
}

--
- Mark ->
--

Nov 13 '05 #5
On 1 Dec 2003 03:52:40 -0800, ri**********@ho tmail.com (Neo) wrote:
Dear All,
I want to know how a subroutine should return an array of values to
the main program.
From the main program, I call a sub-routine 'get_sql' which then
fetches data from oracle db using oci8 routines. The output resides in
a structure defined within the sub-routine. Now I want this structure
to be returned to main program so that I can assing output data to
variables in main program and do some manipulation. Can any body guide
me about how to do it.

Make up your mind. Do you want to return an array or a structure?

Returning a structure makes for simpler code (but not necessarily
efficient code). You return the structure with a return statement
like
return name_of_my_stru ct;
This will work even if the structure contains one or more arrays.

Returning an independent array can be more complicated. Among the
options are

Define the array in the function as static. This will insure the
contents of the array survive past the end of the function.

Allocate the array using malloc or one of its cousins. You can
then return the address of the array to the calling function which
will be responsible to free() the allocated memory when it is no
longer needed.

Define the array in the calling function and pass it to the called
function. The called function will then be able to update the array
directly and it does not need to be returned explicitly.

Define the array at file scope (a global array). The called
function will then be able to update the array directly and it does
not need to be returned explicitly.
<<Remove the del for email>>
Nov 13 '05 #6
"nobody" <no****@nowhere .non> wrote in
news:tE******** ************@tw ister01.bloor.i s.net.cable.rog ers.com:

int main(void)
{
struct WrapArr arr;
struct WrapArr brr;

brr = foo(&arr);

----------------^---
To be consistent with declaration, it should be
brr = foo(arr);
Though I prefer passing pointer(s) in this case
(as Mark McIntyre suggested), not structs themselves.


You are right! Sorry for the bad mistake.

--
- Mark ->
--
Nov 13 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
3612
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
7
1808
by: nafri | last post by:
hello all, I want to create a function that returns the first element of the Array that is input to it. However, the Input Array can be an Array of points, double, or anyother type, which means the return type of the function depends on the type of the objects the Input array holds. I can have the return type as Object, but it has problems like late binding and more importantly the client has to always Cast it. For example. class...
1
1153
by: moondaddy | last post by:
I need to return a nested string array from a function and am getting hung up on syntax. Here's a simple example of a function that returns the array and how I'm trying to call it. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim arr()() As String = Me.TestArr1 End Sub Private Function TestArr1() As String
5
2652
by: Sam | last post by:
Hi All I have couple of question regarding property of a class and structures. **** ---- Here is my class and structure ---- ***** 1. Public Structure MyPoint 2. Dim p As Point 3. Dim ptColor As Color 4. End Structure
8
2229
by: solomon_13000 | last post by:
The code bellow functions well. However if I want to obtain a return value using the code bellow, how is it done? <% Sub RunQueryString (pSQL,parms) on error resume next Set conn = Server.CreateObject("ADODB.Connection") conn.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("/db/upload/stelladb.mdb") & ";" Set cmd = Server.CreateObject("adodb.command")
5
11693
by: samoore33 | last post by:
I use the code below to search through a DataSet: Dim t As DataTable t = result.Tables("State") Dim strExpr As String strExpr = "id = '" & theState.ToString() & "'" Dim foundRows() As DataRow foundRows = t.Select(strExpr) This of course returns foundRows. My problem is that I need to return
10
5616
by: Raj | last post by:
I need a VB function to return array of collections like Private Type Employee empname as string address as string salary as integer deptno as integer End Type dim employees() as Employee
20
9001
by: Andrew Morton | last post by:
Is it possible to have two function declarations which take the same parameters but return different types depending on how the function is used? function f(x) as string ' return a string end function function f(x) as string() ' return an array of strings end function
5
2383
by: Detlev808 | last post by:
Hello, I am attempting to write an awesome perl script. Before it can do anything useful, it must first be able to read in a file, and write out a file (Note: I am NOT talking about text files). Here are the two subroutines I wrote to try to do this: sub Load { my $file = &Prompt("File Name?"); open(INFO, $file); # Open the file my @lines = <INFO>; # Read it into an array close(INFO);
1
1362
by: kirilogan22 | last post by:
Okay first of the variables that I have: they are all structures ex. ALL.vehicles.cars has some functions and and variables/arrays ex. ALL.vehicles.boats is the same structure as .cars ex. ALL.vehicles.cars.price(array) ALL.vehicles.boats will also have price as an array I have multiple buttons on a Windows Application form, each button corresponds to one of these structures variable, since I need to do a lot of calculations with...
0
9389
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,...
0
10149
Oralloy
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...
0
10003
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8825
agi2029
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...
1
7370
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
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();...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3529
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2797
bsmnconsultancy
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.