Re: why do the following crash
- From: Philip Potter <pgp@xxxxxxxxxxxx>
- Date: Mon, 31 Mar 2008 17:38:35 +0100
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
.
- References:
- why do the following crash
- From: parag_paul@xxxxxxxxxxx
- Re: why do the following crash
- From: Bartc
- why do the following crash
- Prev by Date: Re: strcat strncat and strlen
- Next by Date: Re: Convert native character string to ASCII array of integers
- Previous by thread: Re: why do the following crash
- Index(es):
Relevant Pages
|