Go Premium for a chance to win a PS4. Enter to Win

x
Solved

# Array element as function parameter

Posted on 2012-04-11
Medium Priority
507 Views
Hi all -
I'm learning C and wanted to pose a question.  Can you pass an array element to another function?   For instance I'm in a 'FOR Loop' and generating the array with random numbers.   I would like to perform different calculations on these elements as they generate.  Can I pass the element value to another function which would perform the calculations?   Or should I save that element to a variable and then calculate returning and re-assigning the variable value back to the array element?   Thanks for the assist!
0
Question by:mojeaux

LVL 31

Accepted Solution

farzanj earned 668 total points
ID: 37833561
Yes, sure you can pass arrays in C.

http://www-ee.eng.hawaii.edu/~tep/EE160/Book/chap7/section2.1.2.html
0

LVL 35

Assisted Solution

sarabande earned 668 total points
ID: 37833634
you also can pass single array elements:
``````void f(int i)
{
...
}

void g()
{
int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7 ,8 , 9 };
f(arr[5]);
}
``````

the integer at arr[5] was passed 'by value' to function f. 'by value' means, the function uses a copy of the integer element.

Sara
0

LVL 3

Assisted Solution

jcgd earned 664 total points
ID: 37834838
void sum10(int *pv) {

*pv = *pv + 10;

}

void main()
{
int v[] = { 0, 1, 2, 3, 4};
for(int x=0;x<5;x++)
{
printf("Before v[%d]=%d",x,  v[x] );
sum10(&v[x]);
printf(" After v[%d]=%d\n",x,v[x]);
}
}
/* Results:
Before v[0] = 0 After v[0] = 10
Before v[1] = 1 After v[1] = 11
.
.
.

*/
0

Author Closing Comment

ID: 37834926
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
###### Suggested Courses
Course of the Month11 days, 9 hours left to enroll