1

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.

Ben313
  • 1,662
  • 3
  • 20
  • 32
  • 1
    You should get a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn properly. – GManNickG Jul 22 '10 at 18:27
  • 1
    @Gman - at least he isn't [teaching a course](http://stackoverflow.com/questions/3311006/strange-c-exception-definition "teaching a course") – Edward Strange Jul 22 '10 at 18:47

3 Answers3

7

What about allocating the memory for your structure ?

something like :

example* teststruct = new example;
teststruct->a = 0;
Max
  • 3,128
  • 1
  • 24
  • 24
4

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.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
3

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
  • 8,994
  • 2
  • 34
  • 51