如何 return 来自另一个 c 文件中的 void 函数的元素数组

How to return array of elements from a void function in another c file

如何 return 来自另一个 c 文件中的 void 函数的元素数组。我的任务是反转 lab8.c 中的数组,然后使用 main.c 显示结果 我不知道如何反转元素或在 main 中打印结果。我的 main 之外的函数不能使用 printf 或 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--;

}

您的代码中有一个错误,reverse() 函数中的 for 循环没有大括号,因此它只执行了 r = a[i] count / 2 次。

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--;
    }
}

并在 main() 中打印结果只是

reverse(x, count);
printf("Reverse of array 1: %i\n", n);
for (i = 0 ; i < count ; ++i)
    printf("%d ", x[i]);
printf("\n");

此外,如果 scanf() 的 return 值未能成功读取您的程序将调用的值,请不要忽略 UNDEFINED BEHAVIOR,你应该从一开始就学习好的做法。