【发布时间】:2015-10-19 20:15:34
【问题描述】:
在这段代码中,我试图模拟一个填充结构数组的任务, ...获得尽可能多的输出是不安全的。
问题是我在调用函数并迭代结果时
显示不同的字符,但在GetSomeTs()的范围内就可以了。
所以就在返回之前,我测试了其中一个元素并打印了正确的值。
这是测试结构。
public unsafe struct T1
{
public char* block = stackalloc char[5];<--will not compile so the process will be done within a local variable inside a method
}
public unsafe struct T1
{
public char* block;
}
static unsafe T1[] GetSomeTs(int ArrSz)
{
char[] SomeValChars = { 'a', 'b', 'c', 'd', 'e' };
T1[] RtT1Arr = new T1[ArrSz];
for (int i = 0; i < RtT1Arr.Length; i++)
{
char* tmpCap = stackalloc char[5];
for (int l = 0; l < 5; l++)
{
SomeValChars[4] = i.ToString()[0];
tmpCap[l] = SomeValChars[l];
}
RtT1Arr[i].block = tmpCap;//try 1
//arr[i].block = &tmpCap[0];//try 2
}
// here its fine
Console.WriteLine("{0}", new string(RtT1Arr[1].block));
return RtT1Arr;
}
但在其他地方使用它打印垃圾。
void Main()
{
T1[] tstT1 = GetSomeTs(10);
for (int i = 0; i < 10; i++)
{
Console.WriteLine("{0}", new string(tstT1[i].block));//,0,5, Encoding.Default));
}
}
【问题讨论】:
标签: c# arrays string character unsafe