c - 将修改后的数组值传递回 C 中的主函数

标签 c arrays function

很抱歉,如果标题仍然不明确。

我正在为学校做这项作业,下面是我定义的函数原型(prototype)、主函数和change_array 函数。

该程序的总体目标是允许用户输入 5 个不同的数字并存储到一个数组中。然后,change_array 函数的作用是将任何低于 10 的数字加倍(乘以 2),但是,它目前没有执行其预期的操作。我真的很困惑,所以我想知道是否有人可以指出我的错误。我并不要求一个确切的答案,我只是需要一些指示和指导。

问题在于change_array函数没有更改用户给出的任何值。例如,如果用户输入“3,5,6,12,32”,我的程序的输出仍然是“3,5,6,12,32”。但我真正想要的是,从change_array函数传回数组后的“6,10,12,12,32”。

已编辑完整程序:

#include <stdio.h>
#define SIZE 5
void fill_array(double x[], int s);
void change_array(double x[], int s);
void print_array(double x[], int s);

main()
{
    double x[SIZE];

    fill_array(x, SIZE);
    printf("The array is as: \n");
    print_array(x, SIZE);
    change_array(x, SIZE);
    printf("After change, the array is: \n");
    print_array(x, SIZE);
}

void fill_array(double x[], int s)
{
    int i=0;

    printf("Please input 5 Non-Negative double numbers\n");
    for (i=0; i<s; i++) {
        printf("Number %d: ", i+1);
        scanf("%d", &x[i]);
        printf("\n");
    }
}

void change_array(double x[], int s)
{
    int i=0;

    for (i=0; i<s; i++) {
        if (x[i] < 10) {
              (x[i] = (x[i] * 2));
        }
    }
}

void print_array(double x[], int s)
{
    int i=0;

    for (i=0; i<s; i++) {
        printf("%ld \t", x[i]);
    }
    printf("\n");
}

我的代码是用 C 编写的。

最佳答案

数组总是通过引用传递,所以这不是问题。当我添加打印函数和额外的结束花括号时,它按预期工作。您能否提供一个最小工作示例(MWE)以便我们可以运行代码? (我知道这可能应该是一条评论,但我还差 3 分才能发表评论)

关于c - 将修改后的数组值传递回 C 中的主函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9640330/

相关文章:

C中的字符指针减法

performance - Oracle Analytic Functions的成本高昂吗?

C - 将函数加载到数据库 - 调用堆栈错误/段错误

c - 指向自定义地址

c - 使用某种互斥体或信号量机制保护警报和 sleep

java - 双数组mongodb 3

javascript - 将 javascript 数组转换为文本区域

arrays - Excel VBA 中的数组函数

javascript - 为什么有时在使用变量之前将 'null' 分配给它

c++ - 如何从 C++ 代码调用 PL/pgSQL 函数