Re: access violation in int array

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



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
.



Relevant Pages

  • Re: Pointers to Arrays
    ... Nice try to work with pointers ... void segregateXY ... I would like to split it into two 1D arrays, ...
    (comp.lang.c)
  • Re: Doubt about arrays name
    ... basicly pointers are arrays and arrays are pointers, ... but "int main" is better. ... In this case, for traversing a string, using int can't ...
    (comp.lang.c)
  • Re: Destructor that implies another destructor call (using new/delete)
    ... and X also internally allocates a few simple arrays ... The power and elegance of STL classes will do proper cleanup of both the pointed objects and the vector storing the pointers automatically. ... int * GetArray1 ...
    (microsoft.public.vc.language)
  • Re: A taxonomy of types
    ... I am describing how to represent the representation (and, ... if the system follows static typing rules (such as in a compiler), ... so, the hardware sees pointers and pointer arithmetic, but the compiler ... "Besides the char types, up to three sizes of integer, declared short int, ...
    (comp.lang.misc)
  • Re: Why is the pointer passed into the function still NULL?
    ... Specifically about pointers to pointers and 2D arrays. ... get_table can't change maintable no matter how many *s the declaration ... Step back a bit and think about a function that takes an int: ...
    (comp.lang.c)