#include <atlstr.h>
#include <iostream>
#include <list>using namespace std;struct test
{
CString str;
int ma;
};
typedef test* PTEST;
typedef list<PTEST> LST;int main()
{
LST lst(3);
for(LST::const_iterator it = lst.begin(); it != lst.end();it++) {
(*it)->ma = 2;
(*it)->str = "Hello";
}
return 0;
}当程序运行到for循环会出现一个异常:
Unhandled exception at 0x0041214d in test1.exe: 0xC0000005: Access violation writing location 0x00000004.
我调试了的,好像是LST lst(3);
没有分配内存。不知道怎么修改,求助 啊
typedef只是声明了别名。
#include <atlstr.h>
#include <iostream>
#include <list>using namespace std;struct test
{
CString str;
int ma;
};
//typedef test* PTEST;list<test> LST;int main()
{
LST lst(3);
for(LST::const_iterator it = lst.begin(); it != lst.end();it++) {
(*it)->ma = 2;
(*it)->str = "Hello";
}
return 0;
}
这个声明是什么意思?LST 不是已经定义了一个list<test>了么
#include <list>
#include <string>
using namespace std;struct test
{
CString str;
int ma;
};
typedef test* PTEST;
typedef list<PTEST> LST;int main()
{
LST lst; PTEST t1 = new test;
t1->ma = 1;
t1->str = "hello 1";
lst.push_back(t1); PTEST t2 = new test;
t2->ma = 2;
t2->str = "hello 2";
lst.push_back(t2); PTEST t3 = new test;
t3->ma = 3;
t3->str = "hello 3";
lst.push_back(t3); for(LST::const_iterator it = lst.begin(); it != lst.end();it++)
{
printf("%d - %s\n", (*it)->ma, (*it)->str);
} delete t1;
delete t2;
delete t3; return 0;
}
for(LST::size_type ix = 0; ix != 2; ++ix)
{
t[ix]->ma= ix+1;
t[ix]->str = "hello"
lst.push_back(t[ix]);
}
但你的写法相当于list<test*>(3) 这样连表本质上只分配了3个指针的空间(12),每个指针都是没有对应内存分配的,你对他们赋值能不出问题么
it->str = "Hello";(*it).ma = 2;
(*it).str = "Hello";
LST lst(3);
int num = 1;
char a = 'A';
for(LST::iterator it = lst.begin(); it != lst.end();it++)
{
(*it) = new test;
(*it)->ma = num++;
(*it)->str = a++;
} for(it = lst.begin(); it != lst.end();it++)
{
cout << (*it)->ma << " " << (LPCSTR)(*it)->str << endl;
} for(it = lst.begin(); it != lst.end();it++)
{
delete (*it);
} lst.erase(lst.begin(),lst.end());