473,654 Members | 3,082 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to return an array from function

Hi mates

I want to know a simple program of return array from function ? Do I
need to use pointer to return the address of the first element in an
array.

Isaac
Nov 13 '05 #1
4 157987
In article <88************ **************@ posting.google. com>, Isaac wrote:
Hi mates

I want to know a simple program of return array from function ? Do I
need to use pointer to return the address of the first element in an
array.

#include <stdlib.h> /* for malloc(), free(), and NULL */

int *int_arr_alloca tor(int length)
{
int *arr;

arr = malloc(length*s izeof *arr);
if (arr == NULL) {
/* handle error */
}

return arr;
}

int main(void)
{
int *myarr;

/* allocate an array of length 10 */
myarr = int_arr_allocat or(10);

/* use the array */

/* free the array */
free(myarr);

return 0;
}
--
Andreas Kähäri
Nov 13 '05 #2
fp*****@yahoo.c o.uk (Isaac) wrote in message news:<88******* *************** ****@posting.go ogle.com>...
Hi mates

I want to know a simple program of return array from function ? Do I
need to use pointer to return the address of the first element in an
array.

Isaac


Hi Isaac,

Besides the technique already posted, which returns a pointer to a
malloced array, there is another simple trick often used to return an
array from a function. It goes this way.

[code not tested]

struct retarr {
char arr_to_be_ret[20]; /* May be nitpicked :) Better still, use the
preprocessor */
};
struct retarr ArrayReturner(v oid);

int main(void) {
struct retarr arrcollect;
arrcollect=Arra yReturner();
/* Do whatever you want with the returned array
arrcollect.arr_ to_be_ret[] */
/* For what to return here, look at the other threads , its not
quite trivial.
However for all purposes, just letting the main fall off is good
enough
for the standard */
}
struct retarr ArrayReturner(v oid) {
struct retarr arrobj;
int i;
for(i=0;i<20;i+ +) { /* Here's why the above comment was valid
i<(what) */
arrobj.arr_to_b e_ret[i]=i; /* Or whatever you want to do with the
array */
}
return arrobj;
}

Regards,
Anupam
Nov 13 '05 #3
fp*****@yahoo.c o.uk (Isaac) wrote in message news:<88******* *************** ****@posting.go ogle.com>...
Hi mates

I want to know a simple program of return array from function ? Do I
need to use pointer to return the address of the first element in an
array.

Isaac


This covers most of the possible variations. The first two methods
are the most common (using pointers to the base type, rather than
pointers to arrays of the base type).

#include <stdlib.h>
#include <stdio.h>

/*
** Allocate space to hold _size_ ints, return pointer to
** base address as function return value. This is the
** most common method.
*/
int *newa1 (size_t size)
{
int *ap;

ap = malloc (sizeof *ap * size);
if (!ap)
{
printf ("newa1: malloc failed\n");
}
return ap;
}

/*
** Allocate space to hold _size_ ints, return pointer to
** base address as function parameter
*/
void newa2 (size_t size, int **ap)
{
*ap = malloc (sizeof **ap * size);
if (!*ap)
{
printf ("newa2: malloc failed\n");
}
}

/*
** Allocate space for fixed-size array of int, return pointer
** to array as function return value. Not generally used,
** since array sizes are fixed and must be known ahead of time.
**
** The declaration reads as
**
** newa3 -- newa3
** is a function -- newa3()
** taking no parameters -- newa3(void)
** returning a pointer -- *newa3(void)
** to a 10 element array -- (*newa3(void))[10]
** of int -- int (*newa3(void))[10]
*/
int (*newa3 (void))[10]
{
int (*ap)[10];

ap = malloc (sizeof *ap);
if (!*ap)
{
printf ("newa3: malloc failed\n");
}
return ap;
}

/*
** Allocate space for a fixed-size array of int, return pointer
** to array as function parameter
*/
void newa4 (int (**ap)[20])
{
*ap = malloc (sizeof **ap);
if (!*ap)
{
printf ("newa4: malloc failed\n");
}
}

int main (void)
{
int *a1, *a2; /* a1 and a2 are pointers to int */
int (*a3)[10], (*a4)[20]; /* a3 and a4 are pointers to arrays of
int */
int i;

a1 = newa1 (10); /* function call */
if (a1) /* test */
a1[0] = 0; /* assignment */

newa2 (20, &a2);
if (a2)
a2[1] = 1;

a3 = newa3 ();
if (a3)
(*a3)[2] = 2;

newa4 (&a4);
if (a4)
(*a4)[3] = 3;

return 0;
}

Important things to remember:

a1, a2 -- pointers to int.
*a1, *a2 -- int values
a3, a4 -- pointers to arrays of int
*a3, *a4 -- arrays of int values

The spaces that a1 and a2 point to may be resized using realloc().
The spaces pointed to by a3 and a4 may not be resized.

*a1 = 0; /* legal, equivalent to a1[0] = 0; */
*a3 = 0; /* illegal; *a3 is an array type, not an int type */

IME, using pointers to arrays (a3 and a4) is not very common, since
the primary reasons you're using dynamic memory are a) you don't know
how much space you'll need until runtime, and b) you want to be able
to resize that space as needed. However, I thought I'd toss that in
for completeness' sake.
Nov 13 '05 #4
In <88************ **************@ posting.google. com> fp*****@yahoo.c o.uk (Isaac) writes:
I want to know a simple program of return array from function ? Do I
need to use pointer to return the address of the first element in an
array.


Show us how you allocate the array, first.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #5

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

Similar topics

5
2928
by: Andrew Poulos | last post by:
If I'm searching for an occurance of a value in a multi-dimensional array how can I get it's index returned as an array, if found? For example, if: foo = new Array(); foo = , 5, , 9, 10]; Array.prototype.findValue = function(val) { // blah }
6
6602
by: Neo | last post by:
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...
8
3264
by: M. Moennigmann | last post by:
Dear all: I would like to write a function that opens a file, reads and stores data into an 2d array, and passes that array back to the caller (=main). The size of the array is not known before opening to the file. I fail to write a function that allocates memory for a 2d array and returns it to main. I was trying to pass a pointer to the array back to main, but main cannot access the data. The simplified code (no opening of file, but...
23
3583
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;
31
2601
by: CeZaR | last post by:
Hi, How can i specify the return type of a function returning a managed array of chars. If i try to write: "char __gc func()" i get an error! How can i do that? Thanks!
4
40844
by: Woody Splawn | last post by:
How would I pass an array back to a sub routine from a function? That is, I have a function that looks like this Public Function arrayTest() As Array Dim states() As String = { _ "AZ", "CA", "WA" _ } Return states End Function
7
1802
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...
7
5814
by: ashu | last post by:
look at code #include<stdio.h> int *mult(void); int main(void) { int *ptr,i; ptr=mult; for(i=0;i<6;i++) { printf("%d",*(ptr++));
18
4044
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
0
8372
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8285
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
8706
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...
1
8475
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6160
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
5621
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
4293
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2709
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1592
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.