You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组与函数结合使用问题:代码无法运行,需按当前方式修复

Fix for Your C Code Issue

Hey there, I see the problem right away—your function call in main is written incorrectly, which is why the code isn't running as expected. Let's break this down and fix it while keeping your original approach intact.

The Root Problem

In your main function, this line:

int total(array2, 3);

isn't calling your total function. Instead, the C compiler interprets this as a variable declaration (you're accidentally declaring an int variable named total followed by an old-style, irrelevant function prototype). That's why your sum calculation never actually executes.

How to Fix It

Follow these simple steps to get your code working, without changing your core implementation:

  • Remove the int keyword when calling the function—this tells the compiler you're executing the function, not declaring a variable.
  • Optional but highly recommended: Capture the return value and print it out, otherwise you won't see the result of your sum calculation.

Here's the corrected full code:

#include <stdio.h>
#include <stdlib.h>

int total(int arr[3], int size_of_array){
    int i=0;
    int total=0;
    for(i=0;i<size_of_array;i++){
        total+=arr[i];
    }
    return total;
}

int main(){
    int array2[3]= {0,1,8};
    // Correct function call: no int keyword, and we capture/print the result
    int sum_result = total(array2, 3);
    printf("The total sum is: %d\n", sum_result);
    
    // Alternate direct call if you don't want a separate variable:
    // printf("The total sum is: %d\n", total(array2, 3));
    return 0;
}

A Quick Side Note

Just to clarify: Even though you wrote int arr[3] as the first parameter, the compiler will treat this as a pointer (int* arr) under the hood. But since you specified you need to keep your current approach, this is totally fine and doesn't break your code's functionality.

内容的提问来源于stack exchange,提问作者blackwater7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:08:30