#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.

解决方案 »

  1.   

    结构体里面不要用CString改成TCHAR或者CHAR
      

  2.   


    我调试了的,好像是LST lst(3);
    没有分配内存。不知道怎么修改,求助 啊
      

  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;
    }
      

  4.   

     LST lst(3);
    这个声明是什么意思?LST 不是已经定义了一个list<test>了么
      

  5.   

    #include <iostream>
    #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;
    }
      

  6.   

    楼上的能否改成一个for循环来赋初值呢?PTEST t[3] = new PTEST;
    for(LST::size_type ix = 0; ix != 2; ++ix)
    {
       t[ix]->ma= ix+1;
       t[ix]->str = "hello"
       lst.push_back(t[ix]);
    }
      

  7.   

    你错误的原因是:  链表会为每一个元素 在堆里分配空间,但如果这个元素是指针,链表只为这个指针分配空间,但不会为这个指针所对应的实例分配空间list<test>(3)  这种写法不会出问题,因为链表分配了3个test的空间,所以你可以为每个test赋值
    但你的写法相当于list<test*>(3) 这样连表本质上只分配了3个指针的空间(12),每个指针都是没有对应内存分配的,你对他们赋值能不出问题么
      

  8.   

    啊,定义了链表。试试这样:it->ma = 2;
    it->str = "Hello";(*it).ma = 2;
    (*it).str = "Hello";
      

  9.   


    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());