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

C语言数组传参修改异常求助:修改后数组结果不符预期

C语言数组传递修改后结果错误的问题排查与修复

问题分析

你的代码存在两个关键错误,直接导致输出结果不符合预期:

  1. 数组初始化越界,未正确赋值目标元素
    在main函数的初始化循环中,你写了a[SIZE] = i;——数组的合法下标范围是0到SIZE-1(这里SIZE=5,即0-4),a[SIZE]属于越界访问,会修改数组之外的内存区域。而且你始终给同一个越界位置赋值,真正需要初始化的a[0]到a[4]根本没被赋值,这些元素的值是随机的垃圾值。你打印的a[SIZE]虽然显示0-4,但这和数组本身的元素毫无关系。

  2. modifyArray函数逻辑偏离需求
    你写的b[j] = j *= 2;是把循环下标j翻倍后赋值给数组元素,而不是将原数组元素的值翻倍,完全违背了“把数组元素值翻倍”的初衷。另外函数里直接用宏定义的SIZE而非传入的参数size,虽然这次参数值和SIZE一致,但这种写法既不灵活也不符合代码规范。

修正后的代码

// program to pass arrays and individual array elements to functions
#include <stdio.h>
#include <stddef.h>
#define SIZE 5                          // define system constant

// 函数声明放在main外部更规范
void modifyArray(int b[], size_t size);

int main(void)
{
    int a[SIZE];

    puts("Effects of passing the entire array by reference:\nThe values of the original array are:");
    // 正确使用循环下标初始化数组元素
    for (size_t i = 0; i < SIZE; ++i) {
        a[i] = i;
        printf("%3d\n", a[i]);
    }
    puts("");                           // 输出空行
    puts("The values of the modified array are:");

    modifyArray(a, SIZE);
    for (size_t i = 0; i < SIZE; ++i) {
        printf("%3d\n", a[i]);
    }
}

void modifyArray(int b[], size_t size)
{
    // 使用传入的size参数,将原数组元素值翻倍
    for (size_t j = 0; j < size; ++j) {
        b[j] *= 2;
    }
}

修正后运行结果

Effects of passing the entire array by reference:
The values of the original array are:
  0
  1
  2
  3
  4

The values of the modified array are:
  0
  2
  4
  6
  8

内容的提问来源于stack exchange,提问作者Dr. H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:01:29