Reputation: 69
How to return array of elements from a void function in another c file. My assignment is to reverse the array in lab8.c and then use main.c to show the results I have no idea how to reverse the elements or print the results in main. Functions outside of my main cannot use printf or scanf
main.c
#include <stdio.h>
#include "lab8.h"
int main(void) {
int x[100];
int y[100];
int n = 0;
int count, i, product;
printf("Enter the length of both arrays\n");
scanf("%d", &count);
printf("Enter the %i elements of the first array\n", count);
for(i=0; i<count; i++){
scanf("%i", &x[i]);
}
printf("Enter the %i elements of the second array\n", count);
for(i=0; i<count; i++){
scanf("%i", &y[i]);
}
product = inner_product(x, y, count);
printf("Inner product of first array and second: %i\n", product);
printf("Enter the %i elements of the array\n", count);
for(i=0; i<count; i++){
scanf("%i", &n[i]);
}
reverse(n, count);
printf("Reverse of array 1: %i\n", n);
return(0);
}
lab8.c
#include <stdio.h>
#include "lab8.h"
int inner_product(int a[], int b[], int count){
int i;
int result = 0;
for( i=0; i<count; i++){
result = result + (a[i] * b[i]);
}
return result;
}
void reverse(int a[], int count){
int i, r, end = count - 1;
for(i=0; i<count/2; i++)
r = a[i];
a[i] = a[end];
a[end] = r;
end--;
}
Upvotes: 1
Views: 4370
Reputation: 53006
There is one mistake in your code, the for
loop in the reverse()
function has no braces and hence it's just executing r = a[i]
count / 2
times.
void reverse(int a[], int count) {
int i, r, end = count - 1;
for (i = 0 ; i < count / 2 ; i++) {
r = a[i];
a[i] = a[end];
a[end] = r;
end--;
}
}
and to print the result in main()
just
reverse(x, count);
printf("Reverse of array 1: %i\n", n);
for (i = 0 ; i < count ; ++i)
printf("%d ", x[i]);
printf("\n");
also, do not ignore the return value of scanf()
if it doesn't succeed at reading the values your program will invoke UNDEFINED BEHAVIOR, you should learn good practices right from the beginning.
Upvotes: 0