473,503 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

passing an array to a function?

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
8 29012
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
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
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

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

Similar topics

3
14906
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
58
10046
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 starting point. void TheMainFunc() { // Body of...
8
4093
by: kalinga1234 | last post by:
there is a problem regarding passing array of characters to another function(without using structures,pointer etc,).can anybody help me to solve the problem.
10
3123
by: Pete | last post by:
Can someone please help, I'm trying to pass an array to a function, do some operation on that array, then return it for further use. The errors I am getting for the following code are, differences...
6
12647
by: DeepaK K C | last post by:
Could anybody tell me how to pass array to a function by value? -Deepak
2
4824
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 follows: typedef struct tag_scanparm { short...
11
8093
by: John Pass | last post by:
Hi, In the attached example, I do understand that the references are not changed if an array is passed by Val. What I do not understand is the result of line 99 (If one can find this by line...
20
2147
by: jason | last post by:
Hello, I'm a beginning C programmer and I have a question regarding arrays and finding the number of entries present within an array. If I pass an array of structures to a function, then...
8
3483
by: S. | last post by:
Hi all, Can someone please help me with this? I have the following struct: typedef struct { char *name; int age; } Student;
4
5287
by: arnuld | last post by:
I am passing an array of struct to a function to print its value. First I am getting Segfaults and weired values. 2nd, is there any elegant way to do this ? /* Learning how to use an array...
0
7280
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,...
0
7330
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...
0
7460
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5578
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,...
1
5014
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...
0
4672
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...
0
3167
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3154
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.