c#中一个未赋值的问题

来源:百度知道 编辑:UC知道 时间:2024/05/13 03:35:19
static void Main(string[] args)
{
int[] p;
for (; ; )
{
if (p[0] == 2)
break;
p = new int[7];
p[0] = 2;
Console.WriteLine(p[0]);
Console.Read();
}
}

这是一个很简单的程序,但是编译的时候总是说我的 if (p[0] == 2)中的p[0]是“Use of unassigned local variable 'p'?”请问是怎么回事?谢谢!

int[] p 需要初始化 元素个数,才能使用

使用数组需要先初始化大小,
int[] p = bew int[10]
另外这样写循环不太好,如果要写一个无退出条件循环的话用While(true)吧。

for (; ; )
这是什么意思?
循环可以这样用么?
在之前加上一行p[0] = 0;

int[] p 没有赋值
你可以按照楼上的赋值 int[] p = new int[10];
也可以直接赋值为null int[] p = null; 当然,这样的话程序运行时会报错的,但是编译是完全可以通过的

int[] p还没有new的你就用啊,同学,数组要new了才能用,不然就空指针了,你的程序可以这样写:

static void Main(string[] args)
{
int[] p=new int[7];
for (; ; )
{
if (p[0] == 2)
break;
p[0] = 2;
Console.WriteLine(p[0]);
Console.Read();
}
}
这样可以修正你的错误,不过我总觉得你逻辑上没理清,你的程序是不是要这样写?
static void Main(string[] args)
{
int[] p=new int[7];
do
{
p[0]=int.Parse(Console.Read());
}while(p[0]==2);
Console.WriteLine(p[0]);
Console.Read();
}

static void Main(string[] args)
{
int[] p; //定义一个数组P
for (; ; ) //死循环
{
if (p[0] == 2) //p[0]没有实例化
break;
p = new in