Access Violation with pointers to structures

When trying to use two pointers declared as a struct type, the code compiles fine, but at the first reference to the structure declared last, the program crashes with (I think) exception code 0xc0000005. As far as I can tell, this seems to be EXCEPTION_ACCESS_VIOLATION.

I'm using mingw 5.1.4 under Windows XP SP2. The problem code follows:

1
2
3
4
5
6
7
8
9
10
11
12
struct vertex {
	int x;
	int y;
};

int main(int argc, char *argv[]) {
	vertex *A;
	vertex *B;
	A->x = 1;
	B->x = 2;
}


This code compiles with no errors or warnings.

In this code, line 10 is causing the exception. If I swap lines 7 and 8, then the line 9 causes the exception. I've tried defining two structs, vertex and vertey, both with identical members, and declaring *A as vertex and *B as vertey; this results in the same problem at line 10.

If I declare them as variables, rather than pointers (and replace -> with .) there are no problems. If I remove either declaration (and all references to it), there are no problems.

Am I allowed only one pointer to a struct? Or am I missing something else?
Last edited on
The problem is A isn't pointing to anything sensible. Try
1
2
3
4
5
6
7
8
9
10
11
12
struct vertex {
	int x;
	int y;
};

int main(int argc, char *argv[]) {
	vertex V;
       vertex *A = &V;
	vertex *B = &V;
	A->x = 1;
	B->x = 2;
}
Ah, so the pointer has to point to something. Of course.

To check that I'm following correctly... A is a pointer which will point to a variable of type 'vertex.' But because it hasn't been filled with the address of an existing vertex variable, it could very well be pointing anywhere, including some spot outside the program's allocated chunk of memory. Trying to access something Outside will give an access violation exception.

And any time I use a pointer, I need to have also declared a variable for the pointer to point to--which I didn't do.

Also, by the same reasoning, A points to a garbage address (since I haven't initialized it), and therefore A->x is a garbage value located at the garbage address which is (not) stored in A.

Is that right?

I think that's exactly right. Though I'm just learning C too, so my opinion means little.
Both and A and B were pointing to invalid memory. It's just a fluke the first one didn't cause an exception.

You need to point a pointer to an existing variable, or create memory dynamically for it (the main benefit of pointers).

e.g
1
2
3
vertex *A = new vertex;
A->x = 1;
delete A; // Free Memory to prevent leak 
Topic archived. No new replies allowed.