我在一个类中生成一个全局链表(每个结点是一个结构),然后在另外一个类中一次取出,但是为什么下面的代码有错?(在取的时候总是得到链表最后一个结点的值)?哪儿错了?
typedef struct tagTest
{
int aa;
int bb;
}TEST, far *LPTEST;
typedef CList<LPTEST, LPTEST>CTestList;
//赋值
CTestList TestList;
for(int i = 0; i < 5; i ++)
{
TEST t;
t.aa = i;
t.bb = i * i;
TestList.AddTail(&t);
}
//取出来
POSITION pos = TestList.GetHeadPosition();
int n = TestList.GetCount();
POSITION nowpos = pos;
for(int j = 0; j < n; j ++)
{
nowpos = pos;
LPTEST t = NULL;
t = TestList.GetNext(nowpos);
int x= t->aa; //x总是4,为什么?
int y = t->bb; //y总是16,为什么?
}
typedef struct tagTest
{
int aa;
int bb;
}TEST, far *LPTEST;
typedef CList<LPTEST, LPTEST>CTestList;
//赋值
CTestList TestList;
for(int i = 0; i < 5; i ++)
{
TEST t;
t.aa = i;
t.bb = i * i;
TestList.AddTail(&t);
}
//取出来
POSITION pos = TestList.GetHeadPosition();
int n = TestList.GetCount();
POSITION nowpos = pos;
for(int j = 0; j < n; j ++)
{
nowpos = pos;
LPTEST t = NULL;
t = TestList.GetNext(nowpos);
int x= t->aa; //x总是4,为什么?
int y = t->bb; //y总是16,为什么?
}
{
nowpos = pos; // 你不觉得这个地方有点问题么 ?
LPTEST t = NULL;
t = TestList.GetNext(nowpos);
int x= t->aa; //x总是4,为什么?
int y = t->bb; //y总是16,为什么?
}
int n = TestList.GetCount();
LPTEST t = NULL;
for(int j = 0; j < n; j ++)
{
t = TestList.GetAt(j);
int x= t->aa;
int y = t->bb;
}
仔细看看,你对POSITION 的作用理解有误,POSITION 只需声明一次,用于记录并维护内部状态,不需要再次赋值的LPTEST t = NULL;
POSITION pos = TestList.GetHeadPosition();
do{
t = TestList.GetNext(pos);
int x= t->aa;
int y = t->bb;
}while(pos); 如果用原来的代码:
POSITION pos = TestList.GetHeadPosition();
int n = TestList.GetCount();
//POSITION nowpos = pos;//去掉该行
for(int j = 0; j < n; j ++)
{
//nowpos = pos;//去掉该行
LPTEST t = NULL;
t = TestList.GetNext(pos/*nowpos*/);//修改一下
int x= t->aa;
int y = t->bb;
}
for(int i = 0; i < 5; i ++)
{
TEST t;
t.aa = i;
t.bb = i * i;
TestList.AddTail(&t);
}
这里你添加了地址到链表里。但是for每结束一个循环。你的TEST就把上次的空间释放了。所以你的指针可能就无效了
你用动态分配看看呢》
LPTEST t = new TEST;
因为你每个循环没有DELETE吗。所以就还在啊。然后在你链表用完的时候在释放就好了啊。