Re: access violation in int array
- From: "Doug Harrison [MVP]" <dsh@xxxxxxxx>
- Date: Thu, 02 Aug 2007 22:55:13 -0500
On Thu, 2 Aug 2007 19:58:03 -0700, George
<George@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
Hello everyone,
There is error message when executing my program,
Unhandled exception at 0x00411a49 in test_entern.exe: 0xC0000005: Access
violation reading location 0x00000002.
It is very simple, does anyone know what is wrong with the program?
I have tested that when changing from extern int* p_int to extern int
p_int[16], my program is ok. But I think the two statements should be the
same, right?
foo.c
[CODE]
int p_int [16] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
[/CODE]
goo.c
[CODE]
extern int* p_int;
int main (int argc, char** argv)
{
int i;
int sum = 0;
for (i = 0; i < 16; i++)
{
sum += p_int [i]; // access violation
}
return 0;
}
[/CODE]
That's a classic mistake due to the mistaken notion that arrays and
pointers are the same thing, which unfortunately the linker does not catch.
You must use:
extern int p_int[16]; // or
extern int p_int[];
Either will do. The pointer declaration attempt is no good because it
essentially creates a union with the pointer object overlaying the start of
the array. To see what I mean, replace your main with:
printf("%p\n", p_int);
For more on this and other pointer/array info, see:
6. Arrays and Pointers
http://c-faq.com/aryptr/index.html
--
Doug Harrison
Visual C++ MVP
.
- Follow-Ups:
- Re: access violation in int array
- From: George
- Re: access violation in int array
- Prev by Date: Re: Exposing a c++ enum in a managed c++ assembly
- Next by Date: Re: access violation in int array
- Previous by thread: Re: TextBox MaxLength over 32767 has no effect
- Next by thread: Re: access violation in int array
- Index(es):
Relevant Pages
|