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

C语言获取用户成绩数组时size值异常问题求助

问题分析与修复方案

你的代码里size变成随机值的核心原因是数组越界访问导致内存被非法覆盖,具体问题和修复步骤如下:

核心问题点

  • 未分配内存的全局数组array
    全局声明的float array[];是不完整类型,没有实际内存空间。当你用scanf往array[j]写入数据时,会越界访问到相邻全局变量(比如size)的内存区域,直接篡改了size的值,这就是它变成随机大数值的根源。
  • 依赖全局变量默认初始化
    虽然全局变量j默认会被初始化为0,但依赖这种隐式初始化是不良编程习惯,容易引发难以追踪的问题。
  • 未根据输入动态分配数组空间
    你需要根据用户输入的size来匹配数组的实际大小,而非使用空的全局数组。

修复后的代码(动态内存分配版)

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

float average(int size, float array[size]);

int main()
{
    int size;
    int j = 0; // 局部变量显式初始化
    float *array;

    printf("Hello there\nenter the number of grades you want to get average\n");
    scanf("%d", &size);

    // 根据输入的size动态分配数组内存
    array = (float *)malloc(size * sizeof(float));
    if (array == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    printf("\nenter the grades\n");
    while(j < size)
    {
        scanf("%f", &array[j]);
        j++;
        printf("size and j are %d and %d\n", size, j);
    }

    // 释放动态分配的内存,避免内存泄漏
    free(array);
    return 0;
}

可选修复方案(变长数组版,C99及以上支持)

如果使用C99及更高标准,也可以用变长数组(VLA),无需手动管理内存,但注意VLA受栈空间限制,不适合过大的size:

#include <stdio.h>

float average(int size, float array[size]);

int main()
{
    int size;
    int j = 0;

    printf("Hello there\nenter the number of grades you want to get average\n");
    scanf("%d", &size);

    float array[size]; // 根据size在栈上分配数组空间

    printf("\nenter the grades\n");
    while(j < size)
    {
        scanf("%f", &array[j]);
        j++;
        printf("size and j are %d and %d\n", size, j);
    }

    return 0;
}

关键注意事项

  • 尽量避免使用全局变量,优先使用局部变量并显式初始化。
  • 动态分配的内存必须用free释放,防止内存泄漏。
  • 若处理大量数据,优先选择动态内存分配而非变长数组,避免栈溢出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:55:08