473,758 Members | 2,401 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 29064
Tweaxor <ph****@yahoo.c om> 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.hel sinki.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_f unction(unsigne d 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_f unction(array, sizeof(array));
generic_array_f unction(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.l earn.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.co m (Tweaxor) wrote in message news:<1c******* *************** ****@posting.go ogle.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.c om> schrieb im Newsbeitrag
news:1c******** *************** ***@posting.goo gle.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?

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******@netwa y.at> wrote in message news:<3f******* *************** *@newsreader02. highway.telekom .at>...
"Tweaxor" <ph****@yahoo.c om> schrieb im Newsbeitrag
news:1c******** *************** ***@posting.goo gle.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?

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.c o.in> scribbled the following:
li************* **@yahoo.com (August Derleth) wrote in message news:<b6******* *************** ***@posting.goo gle.com>...
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.hel sinki.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******@netwa y.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*******@free net.de)
Nov 13 '05 #8
Irrwahn Grausewitz <ir*******@free net.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*******@free net.de)
Nov 13 '05 #9

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

Similar topics

3
14946
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) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
58
10178
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 code... TCHAR myArray; DoStuff(myArray);
8
4116
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
3169
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 in levels of indirection, so I feel it must have something to do with the way I am representing the array in the call and the return. Below I have commented the problem parts. Thanks in advance for any help offered. Pete
6
12659
by: DeepaK K C | last post by:
Could anybody tell me how to pass array to a function by value? -Deepak
2
4845
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 cmd; short fdc; WORD dsf; short boxcar; short average; short chan_ena;
11
8128
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 number) which is the last line of the following sub routine: ' procedure modifies elements of array and assigns ' new reference (note ByVal) Sub FirstDouble(ByVal array As Integer()) Dim i As Integer
20
2184
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 suddenly I can't use sizeof(array) / sizeof(array) anymore within that function ? Help - What point am I missing ?
8
3502
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
5306
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 of struct */ #include <stdio.h>
0
10076
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...
1
9885
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,...
0
9740
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8744
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
7287
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
6564
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
5332
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3832
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
3
3402
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.