开发者

Why am I getting an error when I try to use my structure?

I have a structure Defined in the Header file for a class i am working in, and i am trying to use the Struct in one of the methods of the class. It looks basically like this:

struct example
{
     double a;
     int b;
     ...
};

in the header above my class definition, an开发者_如何学编程d then in the cpp file, i have:

void exampleclass::test(){

    struct example *teststruct;
    teststruct->a = 0; //This line causes a access violation

}

why do i get an error here? Im sure im doing something clompletly wrong here, and i must say im a huge structure rookie.


What about allocating the memory for your structure ?

something like :

example* teststruct = new example;
teststruct->a = 0;


struct example *teststruct; is a pointer to an instance of the struct example. (By the way, C++ does not require the struct prefix, leave it off.)

So, what example are you pointing at? (Hint: none, you haven't initialized the variable.) You could dynamically allocate one: example *teststruct = new example();, and later delete it: delete teststruct;.*

Of course, you should prefer automatic (stack) allocation over dynamic allocation, and just do:

example teststruct;
teststruct.a = 0;

*And you should never actually handle raw allocations like this. Put them in a smart pointer. At the very least, std::auto_ptr.


As you've written it teststruct points to some random location in memory so accessing it, by doing teststruct->a = 0; takes you into undefined behavior land. So you can have - if you're really lucky - an instant error [like access violation, bus error, segmentation fault etc] or it will run without problems.

You need to either allocate memory for teststruct like Max said or create it on the stack and do something like:

struct example teststruct;
teststruct.a = 0; //This line does not cause an access violation
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜