Functions in C can only return scalars, or, with other words, only one value. In order to return arrays we use pointers and return by reference.
This program illustrates how to use pointers to manipulate arrays in C by adding corresponding elements from two input arrays and storing the results in a third array. The addition is performed in a separate function, demonstrating the concept of passing arrays to functions by reference.
#include <stdio.h> #define SIZE 5 // size of array // Function declaration void addArrays(int size, int *array1, int *array2, int *array3); int main(){ // Input arrays int array_1[] = {1,2,3,4,5}; int array_2[] = {10,20,30,40,50}; // Output array int array_3[SIZE]; // Add array function call addArrays(SIZE, array_1, array_2, array_3); // Print table header printf("Array 1\tArray 2\tArray 3\n"); // Display array element for (int i=0; i<SIZE; i++){ printf("%d\t%d\t%d\n",array_1[i],array_2[i],array_3[i]); } return 0; } // Function definition void addArrays(int size, int *array1, int *array2, int *array3){ for (int i=0; i<SIZE; i++){ array3[i] = array1[i] + array2[i]; } }
Explanation of Code
1. Macro Definition
#define SIZE 5
defines the size of the arrays used in the program for easy modification and readability.
2. Main Function
- Two input arrays,
array_1
andarray_2
, are initialized with integers. - An output array,
array_3
, is declared to store the results of adding corresponding elements ofarray_1
andarray_2
. - The function
addArrays
is called, passing the size and pointers to the three arrays. - The program prints a formatted table showing the elements of all three arrays.
3. Function Declaration and Definition
void addArrays(int size, int *array1, int *array2, int *array3)
:- This function takes the size of the arrays and pointers to the input (
array1
,array2
) and output (array3
) arrays. - A
for
loop iterates through the arrays, and the corresponding elements ofarray1
andarray2
are added and stored inarray3
.
- This function takes the size of the arrays and pointers to the input (
4. Output
The program outputs a table showing the values of the input arrays (array1
and array2
) alongside their summed values in array3
.
Array 1 Array 2 Array 3 1 10 11 2 20 22 3 30 33 4 40 44 5 50 55
Conclusion
This program highlights the efficiency of using pointers to work with arrays in C. By passing arrays by reference, it avoids the overhead of copying data and allows direct manipulation of memory. This technique is crucial for handling large datasets or implementing high-performance algorithms where resource efficiency is vital. Additionally, the program provides a clear example of modular programming, where reusable functions simplify array operations and improve code clarity.