Re: why do the following crash



Bartc wrote:
<parag_paul@xxxxxxxxxxx> wrote in message
news:f5b46a43-52b2-45e2-8bfe-979c20e33dc7@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
File1.c

int arr[80];

File2.c

extern int *arr;
int main()
{
arr[1] = 100;
return 0;
}

The declarations for the arr variable don't match.

Try extern int arr[80] in File2.c.

(I know arrays and pointers are /supposed/ to be interchangeable. But there
is a subtle difference between: int a[80] and int *a)

Arrays and pointers aren't supposed to be interchangable. They don't represent the same concept.

An array of 5 ints is a collection of 5 ints in contiguous memory.

A pointer-to-int is an value which represents the location of an int in memory.

The confusion arises because array accesses are defined in terms of pointers. This means that in an expression like 'arr[2]', the identifier 'arr' which refers to an array "decays" to a pointer-to-first-member; then the subscript operator [] is syntactic sugar for '*(arr + 2)', a pointer arithmetic and dereference operation.

Naturally, in an expression like 'ptr[2]', the rules are the same, except that 'ptr' is already a pointer value and doesn't need to "decay". If 'ptr' points to an element at least 3 before the end of an array, then this is a valid expression.

The FAQ has a very good description of the difference between arrays and poitners in question 6.2.

Philip
.



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: External variables
    ... it's an array of chars and, in function formal arguments, arrays can ... be substituted by pointers. ... global var ... extern int *var ...
    (comp.lang.asm.x86)
  • Re: K&R2, exercise 6.4
    ... arnuld said: ... I am talking about pointers to arrays: ... int arr; ...
    (comp.lang.c)