By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,088 Members | 1,326 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,088 IT Pros & Developers. It's quick & easy.

passing an array to a function?

P: n/a
Hey,
I was trying to figure out was it possible in C to pass the values in an array
from one function to another function. Is the possible in C?

ex. y[7] is the array that holds seven values

If possible how could one pass these seven values in the array
to a function that would check the values.

I tried return y but it didn't work
Nov 13 '05 #1
Share this Question
Share on Google+
8 Replies


P: n/a
Tweaxor <ph****@yahoo.com> scribbled the following:
Hey,
I was trying to figure out was it possible in C to pass the values in an array
from one function to another function. Is the possible in C? ex. y[7] is the array that holds seven values If possible how could one pass these seven values in the array
to a function that would check the values. I tried return y but it didn't work


Well, if your function knows in advance that there will be exactly 7
values, then it's easy.
Simply do something like this:

int main(void) {
int y[7];
doStuff(y);
return 0;
}
void doStuff(int *y) {
/* use y here */
}

The [] operator works on y in doStuff() exactly like it does in main().
The only difference is that there y is in fact a pointer, not an array.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The trouble with the French is they don't have a word for entrepreneur."
- George Bush
Nov 13 '05 #2

P: n/a
Tweaxor wrote:
Hey,
I was trying to figure out was it possible in C to pass the values in an array
from one function to another function. Is the possible in C?

ex. y[7] is the array that holds seven values

If possible how could one pass these seven values in the array
to a function that would check the values.

I tried return y but it didn't work


#include <stdio.h>

void generic_array_function(unsigned int * p_array,
unsigned long quantity)
{
/* Process array p, example: */
printf("p_array[0] = %2d\n", p_array[0]);
return;
}

int main(void)
{
unsigned int array[5] = {4, 3, 2, 1, 0};
unsigned int less[] = {6, 2, 1};
generic_array_function(array, sizeof(array));
generic_array_function(less, sizeof(less));
return 0;
}

In the C language, there is no method to determine the
size of an unknown array, so the quantity needs to
be passed as well as a pointer to the first element.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 13 '05 #3

P: n/a
ph****@yahoo.com (Tweaxor) wrote in message news:<1c**************************@posting.google. com>...
Hey,
I was trying to figure out was it possible in C to pass the values in an array
from one function to another function. Is the possible in C?
It is easy in C. You simply must be aware of a few things first.

ex. y[7] is the array that holds seven values

If possible how could one pass these seven values in the array
to a function that would check the values.
If your function knows y is always going to hold 7 values (and never
less than 7), you can simply pass y as the function's input and not
worry about it.

For example:

#include <stdio.h>

/* print7 takes an array of ints and returns nothing */
void print7(int arr[]);

int main(void)
{
int y[7] = {1,2,3,4,5,6,7};

print7(y);

exit(0);
}

void print7(int arr[])
{
int i;

for(i = 0; i < 7; ++i)
printf("%d\n", arr[i]);
}
If, however, you /don't/ know the size of the array beforehand, you
can do one of two things:

1. Insert a special value at the end of the array so you know you've
reached the end.
2. Pass the size of the array into the function.

In C, strings are implemented the first way: Each string in C is an
array of char that ends with the special value '\0', also called nul.
When a function that works with strings in C reaches nul, it knows the
string has ended.

Functions that work with arrays that are not strings usually take the
length of the array as an additional value.

Let's rewrite our print7 to be printn, which will print arrays of int
of any size we choose:

/* printn takes an array of int and an int and returns nothing. */
void printn(int array[], int size)
{
int i;

for(i = 0; i < size; ++i)
printf("%d\n", array[i]);
}


I tried return y but it didn't work


This opens up another thing you must understand: Temporary storage.
When a function (such as printn) is called, it is given as much
storage as it needs to store all of the local variables it needs (in
this case, the int i). When the function returns, that storage is gone
and can no longer be accessed by anyone unless special steps are
taken.

That special step is the keyword `static': When you make an array
static, you can return it from your function and expect it to be
usable in the function you are returning it to. This is because the
static keyword makes sure the memory is preserved across calls to the
function.

Let's explore this with a trivial function that returns an array of
int:

/* retarr takes nothing and returns a pointer to int (see below). */
int *retarr(void)
{
static int arr[7]; /* arr is static: it will be saved */
int i; /* since i is not static, it will be lost */

for(i = 0; i < 7; ++i)
arr[i] = i;

return arr;
}

Note that retarr actually returns a pointer to int. This is important:
In C, an array is simply an area of memory you can access to store and
retrieve multiple objects of the same type. When you return an array
from a function or pass an array to a function, it `decays' to a
pointer to the first element of that array. Since memory is usually
not preserved once a function exits, the pointer returned when you try
to return an array is a pointer to garbage: It will not point anywhere
useful, and trying to dereference it will lead to an error.

Of course, there is a second way (there's usually more than one way to
do something in C): You can pass in an array (as a pointer) to the
function, and have the function modify that array in place.

A final example:

/* Adds one to all members of an array of ints.
* Takes one array of int and one int. Returns nothing.
*/
void addone(int arr[], int size)
{
int i;

for(i = 0; i < size; ++i)
arr[i] += 1;
}

Remember: When you pass an array to a function, it `decays' to a
pointer to the first element of that array. When you return an array
from a function, it `decays' to a pointer to the first element of that
array.

I hope my post was useful.
Nov 13 '05 #4

P: n/a

"Tweaxor" <ph****@yahoo.com> schrieb im Newsbeitrag
news:1c**************************@posting.google.c om...
Hey,
I was trying to figure out was it possible in C to pass the values in an array from one function to another function. Is the possible in C?

ex. y[7] is the array that holds seven values

If possible how could one pass these seven values in the array
to a function that would check the values.

I tried return y but it didn't work


There are several possibilities:
1) Make the array static in your function and return a pointer to it
(untested, typos likely :))

int *foo(void)
{
static int bar[<some_size>];

/*fill bar with values*/
return bar;
}

2) Put the array into a struct and return the struct

struct tag_intarray
{
int bar[<some_size>];
};

struct tag_intarray foo(void)
{
struct tag_intarray baz;

/*fill the struct with values*/
return baz;
}

3) Define the array in the calling function and pass a pointer to the first
element as well as the size of the array. Others have provided examples for
this method.
Nov 13 '05 #5

P: n/a
"Robert Stankowic" <pc******@netway.at> wrote in message news:<3f***********************@newsreader02.highw ay.telekom.at>...
"Tweaxor" <ph****@yahoo.com> schrieb im Newsbeitrag
news:1c**************************@posting.google.c om...
Hey,
I was trying to figure out was it possible in C to pass the values in an

array
from one function to another function. Is the possible in C?

ex. y[7] is the array that holds seven values

If possible how could one pass these seven values in the array
to a function that would check the values.

I tried return y but it didn't work


There are several possibilities:
1) Make the array static in your function and return a pointer to it


Nitpick: You aren't returning a pointer to an array. You are returning
a pointer to the first member of the array. A pointer to an array
would decay into a pointer to a pointer.
Nov 13 '05 #6

P: n/a
Anupam <an**************@persistent.co.in> scribbled the following:
li***************@yahoo.com (August Derleth) wrote in message news:<b6*************************@posting.google.c om>...
Nitpick: You aren't returning a pointer to an array. You are returning
a pointer to the first member of the array. A pointer to an array
would decay into a pointer to a pointer.
Hi,
Its strange that you should say this. In my opinion it goes like
this :
The identifier denoting the array, can in certain contexts decay
into a pointer to the first element of the array.
However what could be wrong with returning a pointer to an array...
it wud still remain a pointer to the array and not decay into a
pointer to a pointer. Remember, the decay rule is applicable only
once.
So let's say we have

<excerpt>
int a[10];
int (*p)[10];
p=&a;
return(p);
</excerpt>
Why would you say that this would not return a pointer to an array?
Theres no reason it should not.


You are correct. Any type "array of T" decays into a type of "pointer
to T" when used as a value. However this does not mean that "array of
array of T" decays into "pointer to pointer of T", neither does it
mean that "pointer to array of T" decays into "pointer to pointer to
T".
Here's some detail. It is always true that if arr is of type "array of
T", then arr[1] begins exactly sizeof(T) bytes after arr[0]. Let's say
"T" is "array of 10 chars" and sizeof(char *) is 4. This means that
arr[1] begins exactly 10 bytes after arr[0]. However if, when arr is
used as a value, its type would decay to "pointer to pointer to char",
then arr[1] would begin exactly 4 bytes after arr[0]. It can't be both
10 and 4, now can it?

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The obvious mathematical breakthrough would be development of an easy way to
factor large prime numbers."
- Bill Gates
Nov 13 '05 #7

P: n/a
li***************@yahoo.com (August Derleth) wrote:
"Robert Stankowic" <pc******@netway.at> wrote: <snip>
1) Make the array static in your function and return a pointer to it

<unsnipped>
RS> int *foo(void)
RS> {
RS> static int bar[<some_size>];
RS>
RS> /*fill bar with values*/
RS> return bar;
RS> }
</unsnipped>
Nitpick: You aren't returning a pointer to an array. You are returning
a pointer to the first member of the array. Correct.
A pointer to an array
would decay into a pointer to a pointer.

Wrong. A pointer-to-array-of-T is never implicitly converted to a
pointer-to-pointer-to-T. "The Rule" doesn't apply when the address
of an array is taken.

ISO/IEC 9899:1999 6.3.2.1#3:

Except when it is the operand of [...] the unary & operator, [...]
an expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object [...].
Now consider:

#include <stdio.h>
#define ARRSIZE 10

int (*foo(void))[ARRSIZE]
{
static int bar[ARRSIZE];
return &bar;
}

int main( void )
{
printf("%u\n", sizeof *foo() );
printf("%u\n", sizeof **foo() * ARRSIZE );
return 0;
}

Both printf calls should produce the same output.
(Everyone: please correct me if I'm wrong.)

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #8

P: n/a
Irrwahn Grausewitz <ir*******@freenet.de> wrote:

<snip>

ISO/IEC 9899:1999 6.3.2.1#3:

<sigh> Codepage trouble. Hopefully this is readable:

Except when it is the operand of [...] the unary & operator, [...]
an expression that has type "array of type" is converted to an
expression with type "pointer to type" that points to the initial
element of the array object [...].

<snip>
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #9

This discussion thread is closed

Replies have been disabled for this discussion.