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

C#使用未初始化数组触发CS0165错误的修复方法(.NET 8.0)

修复C#中的CS0165错误

问题场景

使用Visual Studio、.NET 8.0环境,编写的C#代码如下:

using System;
using System.Globalization;

namespace Learn
{
    class Program
    {
        public static void Main(string[] args)
        {
           int c;
           int[] arr;
           c = int.Parse(Console.ReadLine());

           for (int i = 0; i <= c - 1; i++)
           {
               arr[i] = int.Parse(Console.ReadLine()); 
           }
       }
   };
}

输入以下内容时触发CS0165错误:

3
1
1
1

错误原因

CS0165错误是使用未赋值的局部变量。代码中仅声明了数组变量arr,但未对其进行初始化——没有为数组分配内存空间,直接通过索引赋值会导致运行时无法找到对应的内存位置。

修复方案

  1. 在获取到输入的c值后,初始化数组,分配对应长度的内存:
    arr = new int[c];
    
  2. 优化循环条件,将i <= c - 1改为i < c,逻辑更简洁直观,效果一致。

修复后的完整代码

using System;
using System.Globalization;

namespace Learn
{
    class Program
    {
        public static void Main(string[] args)
        {
           int c;
           int[] arr;
           c = int.Parse(Console.ReadLine());
           // 初始化数组,分配内存
           arr = new int[c];

           for (int i = 0; i < c; i++)
           {
               arr[i] = int.Parse(Console.ReadLine()); 
           }
       }
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:41:10