tags:

views:

66

answers:

3

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, and 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.

+7  A: 

What about allocating the memory for your structure ?

something like :

example* teststruct = new example;
teststruct->a = 0;
Max
This. Ben, you declared a pointer but didn't point it at an instance of the struct.
Mike Daniels
This worked. dont know why I thought I diddnt need to allocate the memory.
Ben313
@Ben: A pointer has to point at something if you want to use what it's pointing to. Of course, there's no reason to use a pointer here.
GMan
@Ben313 you thought so because you never thought that your inside a class :)
Kedar
+4  A: 

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.

GMan
+3  A: 

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
Eugen Constantin Dinca